Effacer les filtres
Effacer les filtres

problem if statement for loop

2 vues (au cours des 30 derniers jours)
Joel Schelander
Joel Schelander le 7 Avr 2021
I have the following loop. Urbanization is a 412x2 matrix that contains Car IDs and value 0 or 1 if the car is rural or urban. I have 429 cars in ID
and I want to find out which one is rural or urban. However if a car exists in ID but not in Urbanization I want to know that.
I tried using elseif within the loop like below, but then every value in RealID is 99. I want an element in RealID to be 99 if a car is missing.
for u=1:length(Urbanization(:,1))
for v=1:length(ID)
if ID(v)==Urbanization(u,1)
RealID(v)=Urbanization(u,2);
% elseif ID(v)~=Urbanization(u,1)
% RealID(v)=99;
end
end
end

Réponse acceptée

Fuwad Abdul Muyeed
Fuwad Abdul Muyeed le 7 Avr 2021
Since you have two for loops, when u=1, i.e the first ID in Urbanization, the loop runs for the entire length of ID, for which some values are missing in Urbanization. For eg if 1st row in Urbanization is [00204,1], and for ID it is [00204 00205 00206], there are two values in ID which are not present in Urbanization. Thus you will get 99 in 1st index of RealID since 00205 and 00206 are not present. The code below shall work.
for v=1:length(ID)
if any(Urbanization(:,1)==ID(v))
pos=find(Urbanization(:,1)==ID(v));
RealID(v)=Urbanization(pos,2);
else
RealID(v)=99;
end
end

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by