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) ?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Amamcherla Nagaswathi
el 2 de Feb. de 2018
Editada: Amamcherla Nagaswathi
el 3 de Feb. de 2018
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 comentarios
Respuesta aceptada
Stephen23
el 2 de Feb. de 2018
Editada: Stephen23
el 3 de Feb. de 2018
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 comentarios
Stephen23
el 3 de Feb. de 2018
Editada: Stephen23
el 3 de Feb. de 2018
"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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!