problem if statement for loop

2 次查看(过去 30 天)
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

采纳的回答

Fuwad Abdul Muyeed
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by