Matlab: replace the element in the matrix with a minimum row excluding yourself

I want to replace each element with the minimum of my string, except for the element itself.

Example: input In = [1 2 3; 4 5 6; 7 8 9], outputout = [2 1 1; 5 4 4; 8 7 7]

EDIT: no loop for, if only computationally more efficient

+4
source share
2 answers

I did this with two challenges min. you can do it with sort(In,2):

% input matrix
In = [1 2 3; 4 5 6; 7 8 9];
% compute minimum for each row
[val,mincols] = min(In,[],2);
% generate matrix made of minimum value of each row
Out = repmat(val,[1 size(In,2)]);
% find indexes of minimum values
minrows = 1:size(In,1);
minidxs = sub2ind(size(In),minrows,mincols');
% replace minimum values with infs
In(minidxs) = inf;
% find next minimum values
val = min(In,[],2);
% set original minimum elements to next minimum values
Out(minidxs) = val
+1
source

You can use the new feature movminintroduced in MATLAB R2016a to solve this problem with minimal movement:

In = [1 2 3; 4 5 6; 7 8 9];  % Sample data
C = size(In, 2);             % Get the number of columns
out = movmin(In(:, [2:C 1:(C-1)]), [0 C-2], 2, 'Endpoints', 'discard')

out =

     2     1     1
     5     4     4
     8     7     7

, In, , C-1 , . 'Endpoints', 'discard' , .

+3

Source: https://habr.com/ru/post/1675730/


All Articles