Replace value-by-value WITHOUT a loop, from 2 vectors?
조회 수: 3 (최근 30일)
이전 댓글 표시
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
madhan ravi
2019년 4월 26일
편집: madhan ravi
2019년 4월 26일
Illustrate with an example of your input and the desired output.
채택된 답변
Jan
2019년 4월 26일
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))
댓글 수: 0
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!