How to insert strings in array while looping in MATLAB?
How can I insert strings in an array while looping in MATLAB? I know it's very simple but I get a mismatch error. Here is sample code.
s={'asd', 'xyzs', 'pqrs','mn开发者_运维知识库opr'};
for i=1:4
w=randint(1,1,[1,2]);
switch w
case 1
word(i)=s(i);
otherwise
word(i)=3;
end
end
Your problem is that s is a cell and word is not. There are many things you can do to fix this, but an easy way would be to define word to be a cell of size(s). You would then have to convert any numbers into cells before inserting them, which means that your code would look like this:
s={'asd','xyzs','pqrs','mnopr'};
word = cell(size(s));
for i=1:4
w=randint(1,1,[1,2]);
switch w
case 1:
word(i)=s(i);
otherwise
word(i)= num2cell(3);
end
end
精彩评论