2016-01-21 100 views
0

我感興趣的是與每列最小值在同一行的結果值(並且我有很多列,所以我想循環它們,或做rowfun,但我不知道如何得到'結果')。列的值,基於Matlab表中另一列的函數

表A

 
+----+------+------+----+------+------+--------+ 
| x1 | x2 | x3 | x4 | x5 | x6 | result | 
+----+------+------+----+------+------+--------+ 
| 1 | 4 | 10 | 3 | 12 | 2 | 8  | 
| 10 | 2 | 8 | 1 | 12 | 3 | 10  | 
| 5 | 10 | 5 | 4 | 2 | 10 | 12  | 
+----+------+------+----+------+------+--------+ 

解決方案

8 10 12 10 12 8 

我知道,我可以申請rowfun,但我不知道如何得到結果。 然後,我可以做到這一點,但不能在所有列循環:

A(cell2mat(A.x1) == min(cell2mat(A.x1)), 7) 

,我已經試圖使成變量這幾種方法,但我不能讓它工作,使:

A(cell2mat(variable) == min(cell2mat(variable)), 7) 

謝謝!

回答

1

假設你的數據是同質的,你可以使用table2arraymin第二輸出索引結果:

% Set up table 
x1 = [1 10 5]; 
x2 = [4 2 10]; 
x3 = [10 8 5]; 
x4 = [3 1 4]; 
x5 = [12 12 2]; 
x6 = [2 3 10]; 
result = [8 10 12]; 
t = table(x1.', x2.', x3.', x4.', x5.', x6.', result.', ... 
    'VariableNames', {'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'result'}); 

% Convert 
A = table2array(t); 
% When passed a matrix, min finds minimum of each column by default 
% Exclude the results column, assumed to be the last 
[~, minrow] = min(A(:, 1:end-1)); 

solution = t.result(minrow)' 

將返回:

solution = 

    8 10 12 10 12  8 

從文檔min

M = min(A)返回sma最初的元素A

<snip>

  • 如果A是一個矩陣,然後min(A)是包含各列的最小值的行向量。