Storing strings of different sizes in a MATLAB array?

删除回忆录丶 提交于 2019-12-22 09:03:04

问题


I want to be able to store a series of strings of different sizes such as

userinput=['AJ48 NOT'; 'AH43 MANA'; 'AS33 NEWEF'];

This of course returns an error as the number of columns differs per row. I'm aware that all that is needed for this to work is adequate spaces in the first and second rows. However I need to be able to put this into an array without forcing the user to add these spaces on his/her own. Is there a command that allows me to do this? If possible I'd also like to know why this problem doesn't arise with numbers e.g.

a=[1; 243; 23524];


回答1:


You cannot do this with standard Matlab arrays. A string is really just a vector of characters in Matlab. And you cannot have a matrix with rows of different lengths.

You can, however, use a cell array:

userinput={'AJ48 NOT'; 'AH43 MANA'; 'AS33 NEWEF'};

disp(userinput{1});

Be aware that there are many situations where cell arrays don't work like normal arrays.




回答2:


To just answer to your last part of your question; simply because strings may be variable length but numbers (in Matlab) are fixed length. It's one of the main ideas of arrays to let them hold only fixed sizes entities (for example because the need of efficient look up), see more on the topic here.



来源:https://stackoverflow.com/questions/6498332/storing-strings-of-different-sizes-in-a-matlab-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!