Could someone help me identify why my for loop is not working?
8 views (last 30 days)
Show older comments
Good day
I have a for loop to compare two columns in a matrix, but the execution does not seem to work. Could someone please help me to find my mistake. The code looks as follow:
d=[0 1; 0 0; 1 1; 1 0; 0 1; 0 0; 1 1; 1 0]
x1=d(:,1);
y1=d(:,2);
dl = length(d);
for i = dl
if x1(i)==0 && y1(i)==0
p(i)=1
else if x1(i)==1 && y1(i)==1
p(i)=2
else if x1(i)==1 && y1(i)==0
p(i)=3
else if x1(i)==0 && y1(i)==1
p(i)=4
end
end
end
end
end
p'
This is the result: ans = 8×1
0
0
0
3
0
0
0
3
Only the third statement works. Could someone help me identify where I made my mistake, please?
I will essentially use this code for a classification problem, I need to classify lung sounds. The data comes from a text file with a matrix of 4 columns and depending on each audio file a different amount of rows. Each row represent one respiratory cycle. In a text file, the first column is the start of the respiratory cycle, the second column is the end of the respiratory cycle, the third column indicates whether a crackle is present in that cycle (presence=1, absence=0) and the fourth column indicates whether a wheeze is present in that cycle (presence=1, absence=0).
So I want to extract and process the data from the third and fourth column. I am just saying this to explain what the code will be used for.
1 Comment
Kevin Chng
on 12 Oct 2018
Hi,
d=[0 1; 0 0; 1 1; 1 0; 0 1; 0 0; 1 1; 1 0]
x1=d(:,1);
y1=d(:,2);
dl = length(d);
for i = 1:1:dl
if x1(i)==0 && y1(i)==0
p(i)=1
elseif x1(i)==1 && y1(i)==1
p(i)=2
elseif x1(i)==1 && y1(i)==0
p(i)=3
elseif x1(i)==0 && y1(i)==1
p(i)=4
end
end
in your for loop, you direct assign i = dl, it means that you are only compare the last element of x1 and y1. Other than that, you may use more simple way to design your ifelse loop.
Accepted Answer
Kevin Chng
on 12 Oct 2018
Edited: Kevin Chng
on 12 Oct 2018
Hi,
d=[0 1; 0 0; 1 1; 1 0; 0 1; 0 0; 1 1; 1 0]
x1=d(:,1);
y1=d(:,2);
dl = length(d);
for i = 1:1:dl
if x1(i)==0 && y1(i)==0
p(i)=1
elseif x1(i)==1 && y1(i)==1
p(i)=2
elseif x1(i)==1 && y1(i)==0
p(i)=3
elseif x1(i)==0 && y1(i)==1
p(i)=4
end
end
in your for loop, you direct assign i = dl, it means that you are only comparing the last element of x1 and y1. Other than that, you may use more simple way to design your ifelse loop.
accept my answer if it is working for you.
See Also
Categories
Find more on Thermodynamics & Statistical Physics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!