How can I use the same script for multiple different matrix arrays at once?

1 view (last 30 days)
I have matrix arrays of values labelled: Y00, Y01.....Y24, Y25. With each array, I want to take the largest value and its row location. Instead of repeating this function for each array, given the arrays are numbered sequentially I was hoping for some kind of function that takes this into account.
  1 Comment
Stephen23
Stephen23 on 2 Sep 2021
Edited: Stephen23 on 2 Sep 2021
"I have matrix arrays of values labelled: Y00, Y01.....Y24, Y25."
And that is the start of your problems.
Numbering variables like that is a sign that you are doing something wrong.
Did you sit and write all of those names out by hand?
"Instead of repeating this function for each array, given the arrays are numbered sequentially I was hoping for some kind of function that takes this into account."
Accessing the varibale names dynamically (e.g. using eval, which other beginners might advise you to use) forces you into writing slow, complex, obfuscated, inefficient code which is liable to bugs and difficult to debug:
The simple and very efficient MATLAB approach is to store your data in one array (e.g. a cell array or an ND numeric array) which you can then trivially and very efficiently accessing using basic MATLAB indexing. Just like MATLAB was designed for.
Advice from other beginners to use eval or similar is best ignored.

Sign in to comment.

Answers (1)

Jan
Jan on 2 Sep 2021
% Move the set of variables to fields of a struct:
NameList = sprintfc('Y%02d', 0:25);
backcd= cd;
cd(tempdir);
save('dummy.mat', NameList{:});
S = load('dummy.mat');
cd(backcd);
% Get the fields as cell array:
Value = struct2cell(S);
nValue = numel(Value);
% Work on the cell elements:
maxValue = zeros(1, nValue);
maxIndex = zeros(1, nValue);
for k = 1:numel(Value)
[maxValue(k), maxIndex(k)] = max(Value{k});
end
Follow Stephen's valuable advice. Do not create variables with indices hidden in their name, but create arrays directly.
eval() is a shot in your knee. The shown workaround using a MAT file is not much smarter also.

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by