problem if statement for loop

2 ビュー (過去 30 日間)
Joel Schelander
Joel Schelander 2021 年 4 月 7 日
回答済み: Fuwad Abdul Muyeed 2021 年 4 月 7 日
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
Fuwad Abdul Muyeed 2021 年 4 月 7 日
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 Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by