Creating dummy variable with a nested for loop

조회 수: 2 (최근 30일)
Henric
Henric 2012년 2월 29일
Hi, this is probably extremely easy but I am pretty new to MatLab so I have to ask. Here is a shortened version of what I am trying to accomplish.
I have 6 companies and 3 years and 1 event day a year per company. (variable: exd 6x3).
I have dates for three years (variable: date1 1x782).
Now I need to create a 6x782 (variable: d) matrix with dummies, where every companies event day each year is equal to one and the rest is equal to zero on each respective row. So every company (row) should have three one's and the rest should be zero.
The two codes below creates the matrice as I want it but they only keeps the one's for the final (3rd) year. They overwrites the two first loops.
I would really appreciate if someone could enlighten me, what have I done wrong?
Thanks
% i=company 1-6
% Q= day 1-782
% y= year 1-3
for i=1:6;
for Q=1:782;
for y=1:3;
if exd(i,y)==date1(1,Q);
d(i,Q)=1;
else d(i,Q)=0;
end
end
end
end
for Q=1:782;
for i=1:6
for y=1:3;
dummy(i,j)=logical(date1(1,Q)==exd(i,y));
end
end
end

답변 (1개)

Oleg Komarov
Oleg Komarov 2012년 2월 29일
For the first company only
ismember(date1,exd(1,:))
Preallocate and use a loop per company.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by