using a function in a for loop
조회 수: 6 (최근 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에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!