Effacer les filtres
Effacer les filtres

Storing string of a loop

33 vues (au cours des 30 derniers jours)
Alejandro Fernández
Alejandro Fernández le 14 Fév 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'}

Réponse acceptée

Stephen23
Stephen23 le 14 Fév 2020
Modifié(e) : Stephen23 le 14 Fév 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'
  1 commentaire
Alejandro Fernández
Alejandro Fernández le 14 Fév 2020
Thank you so so much!!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by