How to replace value of elements from another matrix index while keeping the same original index?
3 views (last 30 days)
Show older comments
Let say I have this matrix:
STAL = [1 3; 2 7; 3 6; 4 2; 5 2; 6 1; 7 4; 8 7]
where
STAL(:,1) is the number of users from 1 to 8 and
STAL(:,2) is the sector information of each user.
Now after long process of algorithm, we will get the following random-generated vectors, for example:
C(1,:) = [0 4 1 0] and
D(1,:) = [1 7 0 6]
where the numbers in these vectors are the number of users (from STAL(:,1)) Now, I want to replace the number of users with the sector information that is available in STAL(:,2) and then do some comparison.
I tried the following:
New_C = STAL(C,2) but it will not work because it is randomly generated and there is zeros in this vector.
Then I tried the following:
x1 = find(C(1,:)~=0);
value1 = C(1,x1);
New_C (1,1:length(STAL(value1,2))) =STAL(value1,2);
New_C = [2 3 0 0]
However, the problem here is the index of C is different than New_C since I am going to do a comparison between C and D and based on this I am going to delete one of the elements of the original C
For example:
if any(New_C(1,:)==2) && any (New_D(1,:)==4)
then I want to delete the element and replace it with zero of vector C when its sector ( STAL(:,2)) equal to 2
C(1,find(New_C(1,:)==3))=0
but it will not work since the index of C is different than New_C
The expected answer that I am looking for is:
I want to delete the user number (STAL(:,1)) of C when its sector equal 3
C = [0 4 0 0]
since
New_C(1,3)=3
Thanks, Khalid
2 Comments
dpb
on 18 Jun 2017
How about showing us an array and then the result expected? Maybe you did, but I can't decipher what the right answer is, sorry.
Accepted Answer
Andrei Bobrov
on 18 Jun 2017
STAL = [1 3; 2 7; 3 6; 4 2; 5 2; 6 1; 7 4; 8 7];
C = [0 4 1 0];
Tr = 3;
New_C = C;
[lo,ii] = ismember(C(:),STAL(:,1));
New_C(lo) = STAL(ii(lo),2);
C(New_C == 3) = 0;
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!