How to use for loop and get the result for each index varian?

조회 수: 2 (최근 30일)
Arif
Arif 2024년 3월 4일
답변: Voss 2024년 3월 4일
Hello, please give me a hint or clue to solve my problem.
Look at picture number 1: I am trying to do 'for' as long as string 'VarianModel' length. Ignore my API syntax and focus to the code which i red-lined. so there will be 4 models that are going to be run. There are :
Model E, Model F, Model G, Model H.
Each model gives a result named 'Optimize value' like as shown in picture number 2. So it will be :
Optimize value (Model E) = 537.5205
Optimize value (Model F) = 561.0191
Optimize value (Model G) = 571.0191
Optimize value (Model H) = 587.5205
But when after running, it only gives the last model's result not as a cell index aray.
PICTURE #1
PICTURE #2

채택된 답변

Voss
Voss 2024년 3월 4일
"after running, it only gives the last model's result"
Of course, because Optimizevalue is overwritten on each loop iteration. If you want to store one value of Optimizevalue for each loop iteration, you'll need to use indexing.
For example, if each Optimizevalue is a scalar number, you can use a 1x4 numeric vector to store them:
Nmodels = numel(VarianModel);
Optimizevalue = zeros(1,Nmodels);
for i = 1:Nmodels
% ...
% ... calculations
% ...
Optimizevalue(i) = % whatever
end
Or, another example, if each Optimizevalue is an array of potentially different size, then you can store them in a 1x4 cell array:
Nmodels = numel(VarianModel);
Optimizevalue = cell(1,Nmodels);
for i = 1:Nmodels
% ...
% ... calculations
% ...
Optimizevalue{i} = % whatever
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by