How can I use the same script for multiple different matrix arrays at once?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2021-9-2
编辑:Stephen23
2021-9-2
"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.
回答(1 个)
Jan
2021-9-2
% 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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!