Matlab找到变量中的最小数字

时间:2015-03-18 16:42:12

标签: matlab

假设我有10个变量,其中包含不同的数字(num1 = 0.4123,num2 = 0.6223,num3等)。如何找到编号最小的变量?我需要使用递归循环还是有任何简单的方法吗?

2 个答案:

答案 0 :(得分:2)

有一堆由不同变量名描述的数字很糟糕。我建议做@LuisMendo建议的事情并将它们全部放入数组中。

但是,如果您不想将所有这些数字打入一个数组,您可以欺骗并保存所有以num开头的变量,然后将其加载回结构中的MATLAB中。通过将结构转换为单元数组,然后转换为数字数组,将结构转换为数组。

完成后,请使用他正在谈论的min来电。换句话说:

save('temp.mat', 'num*'); %// Save all variables with num from workspace to file
s = load('temp.mat'); %// Reload back in as a structure
vals = cell2mat(struct2cell(s)); %// Convert from structure to numeric array
[~,idx] = min(vals); %// Find value that was the minimum
f = fieldnames(s); %// Get all of the variable names
disp(f{idx}); %// Display the variable that has the minimum

idx将是导致最小值的数字。如果要显示导致最小值的变量的实际名称,可以使用fieldnames从结构中检索所有变量的列表,然后使用最小值索引到该值以获得结果

或者,如果你能打字,只需这样做:

vals = [num1 num2 num3 num4 num5 num6 num7 num8 num9 num10];
[~,idx] = min(vals);
disp(['num' num2str(idx)]);

如果您想要找到min的很多变量,那么第一种方式会更好。如果是这种情况,您应该考虑将所有值放在一个数组中并重新制定代码。在代码中声明了很多变量会使它无法管理。

答案 1 :(得分:1)

将所有这些变量作为数字向量的条目会好得多:

 num = [0.4123 0.6223];

然后你会用

[~, result] = min(num);

获取最小元素的索引。

相关问题