フィルターのクリア

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

5 ビュー (過去 30 日間)
Sam Hurrell
Sam Hurrell 2021 年 9 月 2 日
回答済み: Jan 2021 年 9 月 2 日
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
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
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.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by