How to simplify this If command?

I have a string of 36 numbers that I am reading in from a file and each number means something specific. I am trying to write a for loop/if statement combo that reduces the amount of arguments I need within the if statement and then stores it into a struct that I'll later make into a table. I know that I am reading in the data fine and that my varible "s" is the correct string of numbers, but once I enter the for loop I skip over the if statement entirely and display "Inside For" 35 times with no other result. Is there a way to avoid having to state if i == 1 || i == 4....etc? So far my code is as follows:
s = textscan(sentence.data,'%d%d%d%d%f%f%f%d%f%f%f%d%f%f%f%d%f%f%f%d%f%f%f%d%f%f%f%d%f%f%f%d%f%f%f%d','Delimiter',',');
for i = [1:36]
disp('Inside For...'); %these display functions are to check my work
if i == [1:3:36]
disp('Inside IF...'); %never get this message
carnum = s(i);
speed = strcat('car ', carnum, ' speed');
struct(c).(speed) = s(i+1);
struct(c).carnum = carnum;
end
end

 Accepted Answer

Use the any (link) function.
Example:
for i = 1:36
if any(i == 1:3:36)
fprintf('1 = %d\n',i)
end
end
illustrates the idea and the result.

2 Comments

Thank you for your help and I'd hate to ask for more but now after it enters the if statment it doesn't continue to cycle through the for loop. So it only goes through the for loop the one time and I need it to continue to cycle so I can fully parse the data within the string. Is it the other parts of my code within the if statement or am I just missing something trival? Again I appreciate the help.
As always, my pleasure.
My demonstration loop worked without problems.
I suspect the problem is the way textscan returns its results.
Note that (from the documentation):
C = textscan(fileID,formatSpec) reads data from an open text file into a cell array, C.
and ‘C’ is usually a (1x1) cell.
You have several options, one being to address individual elements of ‘C’, using the techniques in: Access Data in Cell Array (link), or using the cell2mat (link) function to transform it into a matrix. (I prefer using cell2mat.) Note that you then need to be more specific about what field (likely column) of the matrix you assign to ‘carnum’.

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2019a

Community Treasure Hunt

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

Start Hunting!