want for loop to stop if k < 4
1 view (last 30 days)
Show older comments
Pedro Almeida
on 1 Feb 2022
Commented: Pedro Almeida
on 1 Feb 2022
This part of the program takes a file, and takes the numbers inside that file and puts it into a matrix. It only works when, in each line, it does this 4 times, how do I make it so, if it does it less than 4 times and the line is empty, it stops the for loop?
while ~feof(fid)
i = i + 1;
linha = fgetl(fid);
for k = 1:4
linha(1) = [];
[valor, linha] = strtok(linha, ',)');
matriz(i,k) = str2double(valor);
end
end
0 Comments
Accepted Answer
Image Analyst
on 1 Feb 2022
Try this:
while ~feof(fid)
i = i + 1;
linha = fgetl(fid);
% Break if the line is empty and we won't be able to get 4 numbers from it.
if isempty(linha)
break; % Break ot of the while.
end
% If we get to here, the line is good and we should be able to get our
% numbers using the poster's original code (hopefully).
for k = 1:4
%linha(1) = []; % Not needed.
[valor, linha] = strtok(linha, ',)');
matriz(i,k) = str2double(valor);
end
end
More Answers (1)
See Also
Categories
Find more on Loops and Conditional Statements 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!