如何一次将同一脚本用于多个不同的矩阵数组?
1 view (last 30 days)
显示较旧的评论
我有标记为:y00,y01 ..... y24,y25的矩阵阵列。对于每个数组,我想占据最大的值及其行位置。给定数组是顺序编号的,而不是重复每个数组的此功能,我希望能够考虑到某种功能。
1条评论
Stephen23
在2021年9月2日
“我有矩阵的数组values labelled: Y00, Y01.....Y24, Y25."
这就是您问题的开始。
这样的编号变量表明您做错了什么。
您是否坐着手工写所有这些名字?
"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."
动态访问Varibale名称(例如,使用eval,其他初学者可能建议您使用)迫使您撰写缓慢,复杂,混淆,效率低下的代码,该代码易于错误,难以调试:
简单且非常有效的MATLAB方法是将您的数据存储在
一
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.
其他初学者使用评估或类似的建议最好忽略。
答案(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);
节省('虚拟.mat', 名单{:});
s =负载('虚拟.mat');
cd(backcd);
%将字段作为单元阵列:
Value = struct2cell(S);
nvalue = numel(value);
% Work on the cell elements:
maxValue = zeros(1, nValue);
maxindex =零(1,nvalue);
为了k = 1:numel(value)
[maxvalue(k),maxindex(k)] = max(value {k});
结尾
遵循斯蒂芬的宝贵建议。不要创建具有隐藏在其名称中的索引的变量,而是直接创建数组。
eval()
是膝盖的射击。使用垫子文件显示的解决方法也不明智。