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

조회 수: 1 (최근 30일)
Rabia Zulfiqar
Rabia Zulfiqar 2020년 5월 16일
편집: Walter Roberson 2020년 5월 17일
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

채택된 답변

Walter Roberson
Walter Roberson 2020년 5월 16일
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
Rabia Zulfiqar
Rabia Zulfiqar 2020년 5월 16일
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 2020년 5월 16일
편집: Walter Roberson 2020년 5월 17일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2020년 5월 16일
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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by