Reputation: 153
I'm trying to write a matlab code to generate some kind of result page in a textfile but there seems to be some basic knowledge gap here (I'm new to matlab). So the thing that has me confused is how matlab handles strings. I thought I could create a vector full of strings e.g. SampleNr = ['sample1','sample2'];
and later take that vector and print out to the file one specific element, e.g. fprintf(fid, '%s', SampleNr(i));
but when I run this I only get the character in position i
in the string instead of the whole string. As I said this is most likely me misunderstanding this concept, and searches on the mathworks site haven't made this clearer to me so I seek the collective wisdom of stackexchange. A MWE would be:
SampleNr = ['sample1','sample2'];
sprintf('%s', SampleNr(2))
A method to get the whole string would be appreciated, but I would also like to have this confusion cleared up if possible, so in the future I can work confidently with strings in matlab. Thanks in advance.
Upvotes: 1
Views: 14089
Reputation: 16035
In matlab a string is an array of characters, so when you write ['sample1','sample2']
, it concatanates 2 strings to make one string 'sample1sample2'
.
To be clear, when you write a string 'sample'
, it is stored like this: ['s','t','r','i','n','g']
To do what you want, you need to use cells:
SampleNr = {'sample1','sample2'}
sprintf('%s', SampleNr{2})
Upvotes: 4