Strings from Loop to array
조회 수: 2 (최근 30일)
이전 댓글 표시
Hey,
I have the following loop:
for i=1:Parameter1
for j=1:Parameter2
Name=['Name_' int2str(i) '_' int2str(j)];
end
end
I want all the Names writen in one array with one column. Means a total of i*j rows.
How can I write this array?
Would appreciate some help!
댓글 수: 3
Stephen23
2022년 5월 9일
Note: Star Strider's answer using COMPOSE (as dpb suggested) is simpler and more efficient than using loops.
dpb
2022년 5월 9일
Yeah, but you don't even need compose here with the new string class --
[I J]=meshgrid(1:3,1:3);
>> Names=string("Name_"+I+"_"+J)
Names =
3×3 string array
"Name_1_1" "Name_2_1" "Name_3_1"
"Name_1_2" "Name_2_2" "Name_3_2"
"Name_1_3" "Name_2_3" "Name_3_3"
>>
letting meshgrid deal with the implicit loop structure. There might even be a way with the new implicit expansion syntax although I've yet to fully grasp when/where it comes into play...let's see what happens if--
>> N1=3;N2=4;
>> string("Name_"+[1:N1]+"_"+[1:N2].')
ans =
4×3 string array
"Name_1_1" "Name_2_1" "Name_3_1"
"Name_1_2" "Name_2_2" "Name_3_2"
"Name_1_3" "Name_2_3" "Name_3_3"
"Name_1_4" "Name_2_4" "Name_3_4"
>>
and "Yes, Virginia, there is a Santa Claus!" :)
채택된 답변
KSSV
2022년 5월 9일
Parameter1 = 5 ;
Parameter2 = 5 ;
Name = cell(Parameter1,Parameter2) ;
for i=1:Parameter1
for j=1:Parameter2
Name{i,j}=['Name_' int2str(i) '_' int2str(j)];
end
end
Name
댓글 수: 0
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!