필터 지우기
필터 지우기

re-indexing slices of a matrix

조회 수: 19 (최근 30일)
LH
LH 2024년 7월 10일 17:29
댓글: Voss 2024년 7월 10일 19:05
Hi all,
I have a matrix A where its second column represents the index of each row. I want to replace these values so that they start from 1. I tried to do this using the code below, but clearly I'm not succeeding.
mainidx = 4; %main indices
desiredidx = 5; %waht i want the indices to be
%the matrix
A = [1 4
4 4
3 4
6 3
3 3
2 1
3 1
7 2
5 2
9 2
5 1
4 1];
%reindexing
for i = 1:mainidx
for j=1:desiredidx
idx = A(:,2)==mainidx;
A(A(:,2)==desiredidx) = mainidx;
A(idx) = desiredidx;
end
end
I want this matrix to look like the following:
A = [1 1
4 1
3 1
6 2
3 2
2 3
3 3
7 4
5 4
9 4
5 5
4 5];
Any help would be appreicted.

채택된 답변

Voss
Voss 2024년 7월 10일 17:56
A = [1 4
4 4
3 4
6 3
3 3
2 1
3 1
7 2
5 2
9 2
5 1
4 1];
A(:,2) = 1+cumsum([false; logical(diff(A(:,2)))]);
disp(A)
1 1 4 1 3 1 6 2 3 2 2 3 3 3 7 4 5 4 9 4 5 5 4 5
  댓글 수: 2
LH
LH 2024년 7월 10일 19:00
Many thanks! This works the way I want.
Voss
Voss 2024년 7월 10일 19:05
You're welcome!

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

추가 답변 (0개)

카테고리

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