Storing string of a loop

34 visualizaciones (últimos 30 días)
Alejandro Fernández
Alejandro Fernández el 14 de Feb. de 2020
Comentada: Alejandro Fernández el 14 de Feb. de 2020
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'}

Respuesta aceptada

Stephen23
Stephen23 el 14 de Feb. de 2020
Editada: Stephen23 el 14 de Feb. de 2020
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'

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by