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 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