how to do for loop 2nd level?

1 view (last 30 days)
Arif
Arif on 11 Mar 2024
Commented: Arif on 16 Mar 2024
hi guys, i want to do :
XY :
AA
AB
AC
AD
..
QQ
but this error happened.
  1 Comment
Arif
Arif on 11 Mar 2024
Here is my code
clc
clear
beam = {'A';'B';'C';'D';'E';'F';'G';'H';'I';'J';'K';'L';'M';'N';'O';'P';'Q'}
column = {'A';'B';'C';'D';'E';'F';'G';'H';'I';'J';'K';'L';'M';'N';'O';'P';'Q'}
for i = 1 : length(beam)
x(i) = string(beam(i))
for j = 1 : length(column)
y(j) = string(column(j))
xy(i) = append(x(i),y(j))
end

Sign in to comment.

Accepted Answer

Rik
Rik on 11 Mar 2024
Edited: Rik on 11 Mar 2024
Your code can be optimized, but here are the minimal changes.
beam = {'A';'B';'C';'D';'E';'F';'G';'H';'I';'J';'K';'L';'M';'N';'O';'P';'Q'};
column = {'A';'B';'C';'D';'E';'F';'G';'H';'I';'J';'K';'L';'M';'N';'O';'P';'Q'};
xy=repmat("",numel(beam)*numel(column),1);
k=0;
for i = 1 : numel(beam)
x = string(beam(i));
for j = 1 : numel(column)
y = string(column(j));
k=k+1;
xy(k) = x+y;
end
end
xy
xy = 289×1 string array
"AA" "AB" "AC" "AD" "AE" "AF" "AG" "AH" "AI" "AJ" "AK" "AL" "AM" "AN" "AO" "AP" "AQ" "BA" "BB" "BC" "BD" "BE" "BF" "BG" "BH" "BI" "BJ" "BK" "BL" "BM"
Now for the more compact version (using implicit expansion and transposing with .'):
beam = {'A';'B';'C';'D';'E';'F';'G';'H';'I';'J';'K';'L';'M';'N';'O';'P';'Q'};
column = {'A';'B';'C';'D';'E';'F';'G';'H';'I';'J';'K';'L';'M';'N';'O';'P';'Q'};
xy = string(beam).'+string(column);
xy = xy(:);
xy
xy = 289×1 string array
"AA" "AB" "AC" "AD" "AE" "AF" "AG" "AH" "AI" "AJ" "AK" "AL" "AM" "AN" "AO" "AP" "AQ" "BA" "BB" "BC" "BD" "BE" "BF" "BG" "BH" "BI" "BJ" "BK" "BL" "BM"
Or perhaps even this:
beam = string(num2cell('A':'Q'));
column = string(num2cell('A':'Q'));
xy = reshape(beam+column.',[],1);
xy
xy = 289×1 string array
"AA" "AB" "AC" "AD" "AE" "AF" "AG" "AH" "AI" "AJ" "AK" "AL" "AM" "AN" "AO" "AP" "AQ" "BA" "BB" "BC" "BD" "BE" "BF" "BG" "BH" "BI" "BJ" "BK" "BL" "BM"

More Answers (0)

Categories

Find more on Symbolic Math Toolbox in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!