Effacer les filtres
Effacer les filtres

if loop to save number or call NaN

2 vues (au cours des 30 derniers jours)
C.G.
C.G. le 9 Juin 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

Réponses (1)

Govind KM
Govind KM le 9 Juin 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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by