using a function in a for loop
3 次查看(过去 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!