필터 지우기
필터 지우기

Left shift is not working

조회 수: 1 (최근 30일)
Ayesa
Ayesa 2011년 12월 14일
Hi. I am trying to left shift of a m by n matrix but its not working.
PP = [1 2 3 4 %PP can be any size
1 2 3 4,
1 2 3 4]
I want:
PP = [1 2 3 4
2 3 4 0
3 4 0 0]
I used following code(Here i have to use loop because PP actually a very large size matrrix):
[rows cols]= size(PP);
B = zeros(size(PP));
for i = 1:rows
B = zeros(size(PP));
PP_shift(i, :) = [PP(i,(cols:-1:i)) B(1,(i-1))];
end
PP_shift
But its showing me error. Can anyone please help me? Thanks.
  댓글 수: 2
Knut
Knut 2011년 12월 14일
I dont have Matlab here, but could you not do something like:
[rows cols]= size(PP);
PP_shift = zeros(size(PP));
for i = 1:rows
PP_shift(i,1:end-i+1) = PP(i,i:end);
end
PP_shift
BTW, there is probably some neat 2d/1d way of indexing PP that will give you the desired result with faster execution. Perhaps ind2sub().
Ayesa
Ayesa 2011년 12월 14일
Thank you so much. It works perfectly. Again many thanks.

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

답변 (1개)

Walter Roberson
Walter Roberson 2011년 12월 14일
If "i" is the number of rows, then why are you using "i" to index the second dimension of B, which is the position for the column number?
Hint: B does not need to be a full-sized array; it could be a vector.
  댓글 수: 2
Ayesa
Ayesa 2011년 12월 14일
I use "i" to index the second dimension of B because for each row of PP_shift, there should be (i-1) column zeros of B inserted. So when rows = 1, B is a empty matrix, rows = 2, B is a 1 by 1 matrix ,when rows = 3, B is a 1 by 2 matrix and so on.
Otherwise how can i do that?
Walter Roberson
Walter Roberson 2011년 12월 14일
Suppose PP is (say) 5 by 3. Then you would create B as 5 by 3 because you create it the same size as PP. Then when you got to row 5 (i=5) you would be trying to index B at (1,i-1) would would be (1,4) which would not exist because B would only be 3 wide.
hint: in your PP_shift line, replace B by the word zeros

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

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by