Storing string of a loop
조회 수: 19 (최근 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'}
댓글 수: 0
채택된 답변
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 Center 및 File Exchange에서 Cell Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!