Filter löschen
Filter löschen

Strings from Loop to array

2 Ansichten (letzte 30 Tage)
Christopher Schoß
Christopher Schoß am 9 Mai 2022
Kommentiert: dpb am 9 Mai 2022
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 Kommentare
Stephen23
Stephen23 am 9 Mai 2022
Note: Star Strider's answer using COMPOSE (as dpb suggested) is simpler and more efficient than using loops.
dpb
dpb am 9 Mai 2022
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!" :)

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

KSSV
KSSV am 9 Mai 2022
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'}

Weitere Antworten (0)

Kategorien

Mehr zu Historical Contests finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by