Howto replace Element with Element from another Vector at the 1st Element's Position

조회 수: 1 (최근 30일)
Let's say I have a Vector with 100 integer Element between 1 & 100 in no particular Order.
A = [1:100];
A = (randperm (length(A)));
my 2nd Vector can be of any length and contains Integer Elements of any size. Let's Make it:
B = randi([1 200],1,250);
e.g. 250 Elements between 1 & 200 in no particular Order.
Elements of a Size beyond the Dimensions of Vector A don't interest me, so
B (B > 100) = NaN;
Here's what I wanna do:
To Replace all Integer Values in Vector B with the Value in Vector A at that Number's Position.
So let's say the First Element of B is 45. I want to replace it with the 45th Element in Vector A.
If the 2nd Element in B is 89, I want it replaced with the 89th Element in Vector A.
etc.
The NaNs just stay NaNs.

채택된 답변

Fangjun Jiang
Fangjun Jiang 2020년 6월 4일
A=10:10:100;
B=[3,10,nan,2,nan];
index=~isnan(B);
B(index)=A(B(index))
B =
30 100 NaN 20 NaN

추가 답변 (0개)

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by