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
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