Storing string of a loop

32 次查看(过去 30 天)
Hello, good morning, everyone. I was wondering if someone could help me.
I have a loop and I need to save in a single-row matrix and as many columns as I enter in the loop by two, a string containing the iteration of the loop I am in and also text.
What I had done was to use A = sprintf () but I don't know how to store the information I get in an array. I leave a short example so you can see what I need to get.
pos = 1;
for i = 1:4
col(pos) = sprintf('X_',i)
col(pos+1) = sprintf('Y_',i)
pos = pos + 1;
end
The resoult should be the next one:
col =
1×8 cell array
{'X_1'} {'Y_1'} {'X_2'} {'Y_2'} {'X_3'} {'Y_3'} {'X_4'} {'Y_4'}

采纳的回答

Stephen23
Stephen23 2020-2-14
编辑:Stephen23 2020-2-14
Your code has multiple bugs, in particular wrong indexing into the cell array, missing format specifier in the |sprintf| format string, and you are overwriting half of your data on each iteration. Try this instead:
num = 4;
col = cell(2,num); % preallocate.
for k = 1:num
col{1,k} = sprintf('X_%d',k); % I fixed your format string.
col{2,k} = sprintf('Y_%d',k); % I fixed your format string.
end
col = col(:).'
Giving this cell array:
col =
'X_1' 'Y_1' 'X_2' 'Y_2' 'X_3' 'Y_3' 'X_4' 'Y_4'

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by