if loop to save number or call NaN

1 view (last 30 days)
C.G.
C.G. on 9 Jun 2023
Answered: Govind KM on 9 Jun 2023
I have 2 variables, both with 8 numbers in them.
I want to create a new variable which has 10 numbers in it using a for and and if loop.
  • If i is present in a, save the number from b with the same index
  • if i is not present in a, write NaN
This should result in a new variable c, which has 10 values in it, where 2 and 7 are presented by NaN.
Can anybody help me write this?
a = [1 3 4 5 6 8 9 10]
b = [1 2 3 3 9 7 2 2]
c = [];
for i = 1:10
%if i is present in a, save the number from b with the same index.
%if i is not present in a, write NaN.
end

Answers (1)

Govind KM
Govind KM on 9 Jun 2023
The following code will give you the desired output :
a = [1 3 4 5 6 8 9 10];
b = [1 2 3 3 9 7 2 2];
c = [];
for i = 1:10
if any(a==i)
c(i)=b(find(a==i));
%If a can contain duplicate elements, you can use
%c(i)=b(find(a==i,1));
%This will give the index of first occurrence of i in a
else
c(i)=NaN;
end
end

Categories

Find more on Loops and Conditional Statements 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!