2017-05-04 59 views
0

數組值我嘗試在一些特定行(行號1,10,12,20,39等,不連續使用線性索引從find替換數組值。但我不知道如何繼續這幾行代碼之後:在一些具體的行替換MATLAB

[valmax, ~]=max(A); %Where A will consist of more than one MAX value 
idxmax=find(A==valmax); 
mclr=repmat([1 0 0],[10 1]); %Create the matrix of my value 
mclr(idxmax,:)=[0 1 0]; %replace the value at idxmax index, this line won't work 

任何想法如何解決這個問題?或者有其他的功能,而不是使用find? 謝謝!

回答

2

可以使用ind2sub的線性指標轉換成排索引:

A = randi(5,[10 3]); % random matrix 
[valmax, ~] = max(A(:)); %Where A will consist of more than one MAX value 
idxmax = find(A == valmax); 
% convert linear index into row index 
[rowmax,colmax] = ind2sub(size(A),idxmax); 
rowmax = unique(rowmax); % get unique rows 
mclr = repmat([1 0 0],[10 1]); %Create the matrix of my value 
mclr(rowmax,:) = repmat([0 1 0],[numel(rowmax) 1]); %replace the value at idxmax index 

但是它的效率更高,直接獲取包含使用any(X, 2)最大值行:

rowmax = find(any(A == valmax,2));