フィルターのクリア

Storing string of a loop

33 ビュー (過去 30 日間)
Alejandro Fernández
Alejandro Fernández 2020 年 2 月 14 日
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'
  1 件のコメント
Alejandro Fernández
Alejandro Fernández 2020 年 2 月 14 日
Thank you so so much!!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by