Running csv file through if else statement
3 views (last 30 days)
Show older comments
My aim is to have code that will run a csv file through an if statement. I have got it to extract the correct information from the file
I have been using the following code:
fid = fopen('eyes.csv');
data = textscan(fid,'%f %f %f %f %f %f %f %f %f %f %f %f %f %*s','Delimiter',',','Headerlines',1);
fclose(fid);
numrows = size(data,1);
for rownum = 1:numrows
thisrow = data(rownum,:);
val1 = thisrow{1};
val2 = thisrow{2};
val3 = thisrow{3};
val4 = thisrow{4};
val5 = thisrow{5};
val7 = thisrow{7};
val8 = thisrow{8};
val10 = thisrow{10};
val11 = thisrow{11};
val12 = thisrow{12};
val13 = thisrow{13};
if val3<=3 && val10<=1.6 && val1<=56
outcome = 'F';
elseif val3<=3 && val10<=1.6 && val1>56 && val2<=0
outcome = 'F';
elseif val3<=3 && val10<=1.6 && val1>56 && val2>0 && val7<=1
outcome = 'F';
etc.
However I get the error:
Operands to the || and && operators must be convertible to logical scalar values.
Error in Untitled (line 18)
if val3<=3 && val10<=1.6 && val1<=56
I don't understand becuase all the data for each variable 3, 1.4, 67 etc. When I change && to &, it only provides me with one result instead of giving me answers to all the cases in the file.
Any advice? Thanks
0 Comments
Answers (1)
Star Strider
on 14 Nov 2018
First, if you are comparing vectors,use one ‘&’, not ‘&&’.
Second, again if you are comparing vectors, you will likely need the any or the related all function, depending on what you are doing.
5 Comments
Star Strider
on 14 Nov 2018
I cannot accurately reproduce the problem you are having without your file.
When I emulate it (as best I can otherwise), you actually are comparing vectors, so you need to decide how you want to do it.
Example —
data = num2cell(randi(9,10));
numrows = size(data,1);
for rownum = 1:numrows
thisrow = data(rownum,:);
val1 = thisrow{1};
val2 = thisrow{2};
L(rownum) = (val1 < 5) & (val2 > 5);
end
all_v = all(L)
any_v = any(L)
See Also
Categories
Find more on Text Data Preparation 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!