필터 지우기
필터 지우기

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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by