フィルターのクリア

want for loop to stop if k < 4

1 回表示 (過去 30 日間)
Pedro Almeida
Pedro Almeida 2022 年 2 月 1 日
コメント済み: Pedro Almeida 2022 年 2 月 1 日
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

採用された回答

Image Analyst
Image Analyst 2022 年 2 月 1 日
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
  1 件のコメント
Pedro Almeida
Pedro Almeida 2022 年 2 月 1 日
I change a few things based on that and it worked, thank you!

サインインしてコメントする。

その他の回答 (1 件)

Benjamin Thompson
Benjamin Thompson 2022 年 2 月 1 日
Use the break command:
if (k < 4) break;
  1 件のコメント
Pedro Almeida
Pedro Almeida 2022 年 2 月 1 日
for it to also work with the correct format, I have to put something else like this, but it gives me an error 'Matrix index is out of range for deletion.' in linha(1) = [ ]; anything else I could try?
while ~feof(fid)
i = i + 1;
linha = fgetl(fid);
for k = 1:4
linha(1) = [];
[valor, linha] = strtok(linha, ',)');
matriz(i,k) = str2double(valor);
if (k < 4) & linha == 0
break
end
end
end

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by