How to make elements of each column zero before nth element ??

1 view (last 30 days)
Hi I am trying to do something like this, I have a matrix where I have to find the min value of each column after that I have to convert elements occuring before minimum values to zero in each column.
For example:
5x4 matrix
[5 12 8 19
4 2 9 22
6 14 7 1
8 16 4 3
10 3 5 5]
The min value in each column is 4,2,4,1
so the new matrix should be
[0 0 0 0
4 2 0 0
6 14 0 1
8 16 4 3
10 3 5 5]
Can someone please help??? i really appreciate your help.Thanks

Accepted Answer

Walter Roberson
Walter Roberson on 16 May 2020
A = [5 12 8 19
4 2 9 22
6 14 7 1
8 16 4 3
10 3 5 5];
A .* ~cumprod(A>min(A,[],1))
SIgh. I suspect that I just answered a homework problem. I will, however, leave it for you to figure out how it works.
  2 Comments
Rabia Zulfiqar
Rabia Zulfiqar on 16 May 2020
Thankyou so much for this but I am not doing any MATLAB assignment I am trying to form an algorithm for my degree project and I got stuck at this:)
Walter Roberson
Walter Roberson on 16 May 2020
Edited: Walter Roberson on 17 May 2020
I will give you the same advice that I give other people:
Get it working first
That is, you have full permission to use loops or slower algorithms, or do things "brute force" ways, write them however you think about them, as long as you concentrate on getting it working. Don't waste days trying to come up with a clever way to do something when it is blocking your progress.
You can always go back later and clean up the code, make it prettier or more efficient or more MATLAB-y. And when you do, preserve a copy of the version you got working for comparison, so that you can test to prove that the new version gets the same results as the version you got working.
Software engineering tests have found that it is typical that about 80% of the execution time is spent in about 20% of the lines of code. It is not productive to spend days making a nice version of a small section of code that will only account for perhaps 1% of the execution time.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 16 May 2020
Here's one way that's easy to understand and implement:
m = [5 12 8 19
4 2 9 22
6 14 7 1
8 16 4 3
10 3 5 5]
columnMins = min(m, [], 1) % Get min value in each column.
for col = 1 : length(columnMins)
row = find(m(:, col) == columnMins(col), 1);
m(1:row-1, col) = 0;
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!