MATLAB Answers

0

There are four char sequences in the name of a matlab variable (say "AaL1.mat" {1} A to I; {2} a to e; {3} low,med,high; {4} 1 to 6 ). How to loop every possible name (from AaL1.mat to IeH6.mat) ?

There are four char sequences in the name of a matlab variable (say "AaL1.mat" {1} A to I; {2} a to e; {3} low,med,high; {4} 1 to 6 ). How to loop every possible name (from AaL1.mat to IeH6.mat) ?

  0 Comments

Sign in to comment.

1 Answer

Answer by Stephen Cobeldick on 2 Feb 2018
Edited by Stephen Cobeldick on 3 Feb 2018
 Accepted Answer

fmt = '%s%s%s%s.mat';
S1 = 'A':'I';
S2 = 'a':'e';
S3 = 'LMH';
S4 = '1':'6';
for k1 = 1:numel(S1)
for k2 = 1:numel(S2)
for k3 = 1:numel(S3)
for k4 = 1:numel(S4)
name = sprint(fmt,S1(k1),S2(k2),S3(k3),S4(k4));
...
end
end
end
end
Make sure that you preallocate any output variables, otherwise this loop will be slow:

  3 Comments

Dear Sir, Huge Thanks for your answer:)
Also, How can we make S1 from A1 to A9. It is not working with S1='A1':'A9';
And how can we proceed S3 if instead of L,M,H we need L,Me,Hig
%%
%Preallocation
name = cell(810,1);
S1 = 'A':'I';
S2 = 'a':'e';
S3 = 'LMH';
S4 = '1':'6';
i=0;
for k1 = 1:numel(S1)
for k2 = 1:numel(S2)
for k3 = 1:numel(S3)
for k4 = 1:numel(S4)
i = i+1;
name{i,1} = sprintf('%s%s%s%s.mat',S1(k1),S2(k2),S3(k3),S4(k4));
...
end
end
end
end
Thank you very much, Sir.
"How can we make S1 from A1 to A9. It is not working with S1='A1':'A9';"
Use a numeric array and change the format string, e.g. (just the relevant lines):
fmt = 'A%d%s%s%s.mat'; % Note 'A%d' at start.
N1 = 1:9;
...
for k1 = 1:numel(N1)
...
sprintf(fmt,N1(k1),...)
...
end
"And how can we proceed S3 if instead of L,M,H we need L,Me,Hig"
For multiple characters (rather then just one character at-a-time) you could use strings or a cell array, e.g. (just the relevant lines):
...
C3 = {'L','Me','Hig'};
...
for k3 = 1:numel(C3)
...
sprintf(fmt,...,C3{k},...) % note {} brackets for cell array indexing!
...
end
...
I would also recommend that you automatically adjust the size of the output array names, so putting it all together you would have something like this:
fmt = 'A%d%s%s%s.mat';
idx = 0;
N1 = 1:9;
S2 = 'a':'e';
C3 = {'L','Me','Hig'};
S4 = '1':'6'
N = numel(N1)*numel(S2)*numel(C3)*numel(S4);
name = cell(N,1); % automatically preallocate the right size
for k1 = 1:numel(V1)
for k2 = 1:numel(S2)
for k3 = 1:numel(C3)
for k4 = 1:numel(S4)
idx = 1+1;
name{idx} = sprintf(fmt,N1(k1),S2(k2),C3{k3},S4(k4));
...
end
end
end
end
Actually working with strings would make this all much simpler, as you could use the same indexing and format type for all four substrings.

Sign in to comment.