You should call the cell's content via str{1} as follows to make it correct:
for str = {'aaa','bbb'}
fprintf('%s\n',str{1});
end
Here's a more sophisticated example on printing contents of cell arrays.
Answer from petrichor on Stack OverflowYou should call the cell's content via str{1} as follows to make it correct:
for str = {'aaa','bbb'}
fprintf('%s\n',str{1});
end
Here's a more sophisticated example on printing contents of cell arrays.
str={'aaa','bbb'};
fprintf('%s\n',str{:});
No need for for loops.
EDIT:
See also: cellfun
For loop in string array
Is it possible to iterate over a cell of strings in order to create new variables?
How does one create an array of strings in a loop? In a better way.
Beginner: How do I loop through strings ?
Or you can do:
for i={'cow','dog','cat'}
disp(i{1})
end
Result:
cow
dog
cat
Your problems are probably caused by the way MATLAB handles strings. MATLAB strings are just arrays of characters. When you call ['cow','dog','cat'], you are forming 'cowdogcat' because [] concatenates arrays without any nesting. If you want nesting behaviour you can use cell arrays which are built using {}. for iterates over the columns of its right hand side. This means you can use the idiom you mentioned above; Oli provided a solution already. This idiom is also a good way to showcase the difference between normal and cell arrays.
%Cell array providing the correct solution
for word = {'cow','dog','cat'}
disp(word{1}) %word is bound to a 1x1 cell array. This extracts its contents.
end
cow
dog
cat
%Normal array providing weirdness
for word = ['cow','dog','cat'] %Same as word = 'cowdogcat'
disp(word) %No need to extract content
end
c
o
w
d
o
g
c
a
t
Hello. I want to make a string array like in the figure below. I think I can do it using a for loop because 'ID_' doesn't change. I try to use something like this but it doesn't work.
for i=1:20
cord(i,1) = {'id_' num2str(i)}
endI would apreciate any kind of help.
Thanks
You just need to add square brackets around the text to concatenate it into a single piece of text. Currently, your right hand side is a 1x2 cell array rather than a 1x1 cell array with a single piece of text.
for i=1:20
cord(i,1) = {['id_' num2str(i)]}
end
If you can use the new string datatype in your workflow, you could just do:
"id_" + (1:20)'
There’s a function called “compose” that you might be interested it.
Hey all, how do I select/index a char from a string?
I've tried doing something like input[i] and iterate over the i, but apparently MATLAB does this indexing differently, and the "i" selects the whole string.
How do I do this? Thanks.