using a function in a for loop
4 ビュー (過去 30 日間)
古いコメントを表示
I have a function that interrogates a file and returns a matrix and a boolean. I would like to run this for 12 different parts of a file. The below gives an error that brace indexing is not supported for this variable type. Is there a way to write the below?
for k = 1 : 12
[CH{k} result{k}] = ytmWdfGetData(fileName, k, 1)
end
0 件のコメント
採用された回答
Image Analyst
2022 年 11 月 14 日
Your simplified code works fine. Watch:
fileName = 'snafu.txt';
for k = 1 : 12
[CH{k} result{k}] = ytmWdfGetData(fileName, k, 1);
end
celldisp(CH)
celldisp(result)
fprintf('Done!\n')
function [out1, out2] = ytmWdfGetData(arg1, arg2, arg3)
out1 = rand;
out2 = rand;
end
Your error comes from some other part of your code.
Please attach the complete error message -- ALL THE RED TEXT. This includes the line number, the actual line of code that threw the error, and the error description itself.
If you have any more questions, then attach your data and code to read it in with the paperclip icon after you read this:
2 件のコメント
Image Analyst
2022 年 11 月 14 日
@Ted HARDWICKE no. Well yes, but they're kludgy and not recommended. For example one way is
for k = 1 : 3
if k == 1
[CH1, result1] = ytmWdfGetData(fileName, k, 1);
elseif k == 2
[CH2, result2] = ytmWdfGetData(fileName, k, 1);
elseif k == 3
[CH3, result3] = ytmWdfGetData(fileName, k, 1);
end
end
その他の回答 (1 件)
Vilém Frynta
2022 年 11 月 14 日
編集済み: Vilém Frynta
2022 年 11 月 14 日
I would recommend define your variables beforehand with zeros(). This way, you may avoid your brace indexing problem. Then you can asign function results to your variables directly from function (v1) or indirectly (v2).
I'll try to show an example:
v1
% Create zeros beforehand, you will asign function results here
CH = zeros(1:12)
results = zeros(1:12)
for k = 1 : 12
[CH(k) result(k)] = ytmWdfGetData(fileName, k, 1)
end
v2 - little diferent version, that I would say is "safer"
% Create zeros beforehand, you will asign function results here
CH = zeros(1:12)
results = zeros(1:12)
for k = 1 : 12
[X Y] = ytmWdfGetData(fileName, k, 1) % Save function results to X and Y
CH(k) = X; % Save X and Y to CH and results
results(k) = Y;
end
If you want different variable type (cell, structure), you can change it as you desire; you can use something else than zeros, jsut define your variables and use indexing.
EDIT: Added second version.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!