How to make specific elements of a matrix zero before nth element?

조회 수: 26 (최근 30일)
Rabia Zulfiqar
Rabia Zulfiqar 2020년 6월 1일
편집: Tommy 2020년 6월 2일
Hi I have a matrix of 24x365. I have an array which reperesents the index of an element in each column.I want to convert all elements to zero in each column which are before that index value.
For example consider a 4x4 matrix.
A=[1 2 3 4
5 6 7 8
9 1 3 4
8 7 5 3]
B=[1,3,2,4] %Index array
so the new matrix should be c which is answer matrix.so the first element in B is the index for column 1.Its value is 1 and as there is no element before 1 so the whole column 1 remains the same in answer matrix C.Now for column 2,the index of the element is 3 so the first and second elemtents of column 2 will become zero in answer matrix C similarly for third column B(3)=2 so column 3 will have its first element as zero. Same condition applies for 4th column that before the 4th element in 4th column every element converts to zero.
Answer matrix:
C=[1 0 0 0
5 0 7 0
9 1 3 0
8 7 5 3]
How can I do that?
  댓글 수: 2
madhan ravi
madhan ravi 2020년 6월 1일
You need to explain more
Rabia Zulfiqar
Rabia Zulfiqar 2020년 6월 1일
Dear Madhan ravi, I have edited my question and added a little bit more explanation.I hope it's cleared now:) but still if you eed more explanation just let me know.

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

채택된 답변

Matt J
Matt J 2020년 6월 1일
편집: Matt J 2020년 6월 1일
[m,n]=size(A);
C=A.*((1:m).'>=B);
  댓글 수: 4
Tommy
Tommy 2020년 6월 1일
If you're referring to what my comment previously said, I edited it out after I saw your updated answer. Sorry for any confusion.
And I suppose that's a (bad?) habit of mine.
Matt J
Matt J 2020년 6월 1일
No problem. Just one of the side effects of real-time editing...

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

추가 답변 (1개)

Tommy
Tommy 2020년 6월 1일
Boring:
C = A;
for i = 1:size(A,2)
C(1:B(i)-1,i) = 0;
end
Ugly:
C = A;
[N,M] = size(C);
C(~any((1:N*M)'>=N*(0:M-1)+B & (1:N*M)'<=N:N:N*M,2)) = 0;
  댓글 수: 1
Matt J
Matt J 2020년 6월 1일
The for-loop will in many cases be the fastest solution, since it requires the least memory accessing and allocation.

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

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by