Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing strings of different sizes in a MATLAB array?

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];

like image 458
straits Avatar asked Jan 20 '23 09:01

straits


2 Answers

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.

like image 102
Oliver Charlesworth Avatar answered Jan 21 '23 23:01

Oliver Charlesworth


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.

like image 45
eat Avatar answered Jan 21 '23 23:01

eat