# how to replace the elements row by rows instead of column by column in matrix

조회 수: 12 (최근 30일)
M.S. Khan . 2019년 7월 20일
댓글: M.S. Khan . 2019년 7월 23일
A =[ 0 0 3 3 3 0 0 3 0 0; 0 0 0 3 3 3 0 3 3 0]
[rows,colms ] = size(A)
for i = 1:rows
for j = 1:colms
index-1 = find(A==3,1,'first')
index_2 = find(A==3,1,'last')
If A(i,j)=3 & A(i,j)==index_1
A(i,index_1:index_2) = A(i,index_1:index_2) +1
end
end
end
it gives me 5th and 18th indices while i want to get row wise like first should be 3rd and last should be 6th.
##### 댓글 수: 2이전 댓글 1개 표시이전 댓글 1개 숨기기
M.S. Khan 2019년 7월 20일
Mr. Madhan Ravi, i want the first 3 in the rows as the lowest element and the last one as the heighest element in each row. and want to add 1 .e.g.
0 0 3 3 3 0 0 3 0 0 => 0 0 4 4 1 1 4 0 0 (i want to add 1 from lowest 3 to highest 3)
0 0 0 3 3 3 0 3 3 0 => 0 0 0 4 4 4 1 4 4 0

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

### 채택된 답변

find(A==3,1,'first')
find(A==3,1,'last')
These lines find linear indices not [row, col] subsets. Linear indices go along all the rows of the first column, then on to the second column and so on.
These two lines also disregard i and j completely, so they always give the absolute first and last linear indices in the entire matrix each iteration (5 and 18).
I dont know what exactly you're trying to achieve, but maybe you need to compare only current row:
index_1 = find(A(i,:)==3,1,'first');
index_2 = find(A(i,:)==3,1,'last');
Look here for explanation on array indexing in Matlab
if A(i,j)=3 & A(i,j)==index_1
This condition compares the value of A(i,j) to 3 and to the first index which equals 3, that makes little sence to me, but i may be missing your intent
If you explain with more detail what you are trying to do, we may be able to help you get to the right solution
##### 댓글 수: 5이전 댓글 4개 표시이전 댓글 4개 숨기기
M.S. Khan 2019년 7월 21일

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

### 추가 답변 (2개)

Bruno Luong 2019년 7월 20일
f = @(A)cumsum(A==3,2)>0;
A = A + f(A).*fliplr(f(fliplr(A)))
##### 댓글 수: 4이전 댓글 3개 표시이전 댓글 3개 숨기기
M.S. Khan 2019년 7월 23일
Dear Bruno, its so complicated. its blowing above my head.
Regards

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

KALYAN ACHARJYA 2019년 7월 20일
편집: KALYAN ACHARJYA 님. 2019년 7월 20일
A=[0 0 3 3 3 0 0 3 0 0; 0 0 0 3 3 3 0 3 3 0]
[rows colm]=size(A);
B=zeros(rows,colm);
for i=1:rows
B(i,i+2:end-3+i)=1;
end
result=A+B
Command Window:
A =
0 0 3 3 3 0 0 3 0 0
0 0 0 3 3 3 0 3 3 0
result =
0 0 4 4 4 1 1 4 0 0
0 0 0 4 4 4 1 4 4 0
>>
##### 댓글 수: 1없음 표시없음 숨기기
M.S. Khan 2019년 7월 21일
Thanks Mr. Kalyan for kind contribution and support

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

### 카테고리

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