Richard Laurant
Richard Laurant

Reputation: 657

Matlab: Find minimum value from a set of values for each column in an array

I have a 2-D array A=zeros(1000,1024). I want to iteratively compute the difference between each of the value of the i-th row (with i=1-999) and the values of 1000th row.

Right now I think of looping over the 1-999 rows, compute the differences of the current row and the 100th row and store it in a seperaate data structure (B=zeros(999,1024)). After, I compute the minimum of each column using another for-loop, which iterates over the columns of B.

Do you know of a more efficient, faster approach?

Upvotes: 0

Views: 624

Answers (3)

Luis Mendo
Luis Mendo

Reputation: 112769

If you only want the minimum of each column, you can save many operations by doing the subtraction at the end:

min(A(1:end-1,:),[],1) - A(end,:)

Upvotes: 3

Divakar
Divakar

Reputation: 221704

Try this -

min(bsxfun(@minus,A(1:999,:),A(1000,:)),[],1)

It seems you want to subtract from the last row, so you can make it general -

min(bsxfun(@minus,A(1:end-1,:),A(end,:)),[],1)

Upvotes: 1

Dan
Dan

Reputation: 45752

This is a classic use case for bsxfun:

M = rand(1000,1024);
V = M(end,:);

MminusV = bsxfun(@minus, M(1:end-1,:), V);

min(MminusV)

Upvotes: 1

Related Questions