필터 지우기
필터 지우기

Strings from Loop to array

조회 수: 2 (최근 30일)
Christopher Schoß
Christopher Schoß 2022년 5월 9일
댓글: dpb 2022년 5월 9일
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
Stephen23 2022년 5월 9일
Note: Star Strider's answer using COMPOSE (as dpb suggested) is simpler and more efficient than using loops.
dpb
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
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
Name = 5×5 cell array
{'Name_1_1'} {'Name_1_2'} {'Name_1_3'} {'Name_1_4'} {'Name_1_5'} {'Name_2_1'} {'Name_2_2'} {'Name_2_3'} {'Name_2_4'} {'Name_2_5'} {'Name_3_1'} {'Name_3_2'} {'Name_3_3'} {'Name_3_4'} {'Name_3_5'} {'Name_4_1'} {'Name_4_2'} {'Name_4_3'} {'Name_4_4'} {'Name_4_5'} {'Name_5_1'} {'Name_5_2'} {'Name_5_3'} {'Name_5_4'} {'Name_5_5'}

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Historical Contests에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by