Rename the indices of a vector in a certain way.

조회 수: 3 (최근 30일)
LH
LH 2024년 7월 4일
댓글: Stephen23 2024년 7월 4일
Hi all,
My code below has a vector A and its index vector idx. It goes throguh the elements of A and when it finds a zero element, it removes its index from the orginal index vector.
My problem here is: suppose the updated index vector is . How can I rename this vector so it increases in an acending order? For example: the first element in the updated index vector is 1, I want this to be 1, the second element in the updated index vector is 3, I want this to become 2, and so on so forth.
%define the index vector
idx = [1 2 3 4 5];
%define the vector
A = [5 0 6 0 3];
%initialise the vector that has all indices of zero elements
zero_indices = [];
%go through the elements of vector A
for uu = 1:numel(A)
%if the element is zero
if A(uu)==0
%assign its index to the zero-elements index vector
zeroindex = uu;
%collect all results from iterations
zero_indices = [zero_indices ; zeroindex];
end
end
%update the original index vector by removing the indicies that correspond
%to zero elements
idx(zero_indices) = [];
%rename the indices os that they beocome 1, 2, 3, ...
Any help would be appreicted.
Thanks.

채택된 답변

Garmit Pant
Garmit Pant 2024년 7월 4일
Hello LH
Given that you have extracted the indices of non-zero elements in the vector ‘A’, you can rename the index vector to have ascending values using the following code-snippet:
% Given non-zero value indices are [1 3 5]
idx = [1 3 5];
% Rename the indices so that they become 1, 2, 3, ...
new_idx = 1:numel(idx);
% Display the updated index vector
disp('Updated index vector:');
Updated index vector:
disp(new_idx);
1 2 3
I hope you find the above explanation and suggestions useful!
  댓글 수: 4
LH
LH 2024년 7월 4일
That's great! Many thanks Garmit!
Stephen23
Stephen23 2024년 7월 4일
The simpler MATLAB approaches:
idx = [1,3,3,5,1,5,3,1]
idx = 1x8
1 3 3 5 1 5 3 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
[~,~,idy] = unique(idx)
idy = 8x1
1 2 2 3 1 3 2 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
idy = discretize(idx,[unique(idx),Inf])
idy = 1x8
1 2 2 3 1 3 2 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by