0

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?

3 Answers 3

3

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,:)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

2 Comments

My solution was wrong actually as I had included the last row into bsxfun. Now its correct but identical to yours :)
@Divakar but Luis' beats them both ;)
1

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)

5 Comments

+1 but I think min(bsxfun(@minus,A(1:end-1,:),A(end,:)),[],1) suits the question better
Do you need the ,[],1?
@Dan That's to prevent min from working along a row if there's just one row
@Dan Sort of got into the habit to specify the dimension to avoid confusion.
@LuisMendo Dan's suggestion works too, but just a safer practice I am trying these days :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.