Replace value-by-value WITHOUT a loop, from 2 vectors?

3 views (last 30 days)
Dear all!
I want replacing the value of the element in vector a with the corresponding value of the element in vector b. Therefore, I have coded like this:
function result=Replace_Value_by_Value(X,a,b)
% Replace the value of the element in vector a
% by the corresponding value of the element in vector b
%length(a) = length(b)
%length(X)>>> length(a)
result=X;
for i=1:size(X,1)
for j = 1:length(a)
if X(i)==a(j)
result(i)=b(j);
end
end
end
end
Example:
X=[1,2,3,4;5,6,7,8;1,4,2,1;6,7,1,2]
a=[1,2,3,4]
b=[100,200,500,400]
Result must be:
result =
100 200 500 400
5 6 7 8
100 400 200 100
6 7 100 200
Is there any other way without using FOR?
Please help. Thank you..
  2 Comments
madhan ravi
madhan ravi on 26 Apr 2019
Edited: madhan ravi on 26 Apr 2019
Illustrate with an example of your input and the desired output.
Nguyen Anh Cuong
Nguyen Anh Cuong on 26 Apr 2019
Example:
X=[1,2,3,4;5,6,7,8;1,4,2,1;6,7,1,2]
a=[1,2,3,4];
b=[100,200,500,400];
result=Replace_Value_by_Value(X,a,b)
Result must be:
X =
1 2 3 4
5 6 7 8
1 4 2 1
6 7 1 2
result =
100 200 500 400
5 6 7 8
100 400 200 100
6 7 100 200

Sign in to comment.

Accepted Answer

Jan
Jan on 26 Apr 2019
X = [1,2,3,4;5,6,7,8;1,4,2,1;6,7,1,2];
a = [1,2,3,4];
b = [100,200,500,400];
[M, ia] = ismember(X, a);
X(M) = b(ia(M))

More Answers (0)

Community Treasure Hunt

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

Start Hunting!