using a function in a for loop
3 views (last 30 days)
Show older comments
Ted HARDWICKE
on 14 Nov 2022
Commented: Image Analyst
on 14 Nov 2022
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 Comments
Accepted Answer
Image Analyst
on 14 Nov 2022
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 Comments
Image Analyst
on 14 Nov 2022
@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
More Answers (1)
Vilém Frynta
on 14 Nov 2022
Edited: Vilém Frynta
on 14 Nov 2022
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 Comments
See Also
Categories
Find more on Logical 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!