if loop to save number or call NaN

3 Ansichten (letzte 30 Tage)
C.G.
C.G. am 9 Jun. 2023
Beantwortet: Govind KM am 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

Antworten (1)

Govind KM
Govind KM am 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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by