Create an array of handle objects using for-loop

4 views (last 30 days)
I created my own handle Class called CModelDeficit, and now want to create an array of this objects with slight difference in parameters:
function M = meta(obj)
M = [];
p = obj.getParameters(); %this gives me parameters of initial object
p(3) = 0.1;
p(4) = 0.1;
M = [M,CModelDeficit(p)]; %CModelDeficit(p) is a constructor of a class with parameters 'p'
p(3) = 0.2;
p(4) = 0.2;
M = [M, CModelDeficit(p)];
end
Calling this function returns me a 1x2 CModelDeficit, just as i wanted it.
But when i try make the very same process using for-loops:
function M = meta2(obj)
M = [];
p = obj.getParameters();
for i = 1:0.1:0.9
for j = 1:0.1:0.9
p(3) = i;
p(4) = j;
M = [M,CModelDeficit(p)];
end
end
end
returns me just an empty vector.
It seems for me very confusing and illogical, that they have different behaviour.
I always thought, that, in such context, for-loop is a nicer way to write functions, then just typing nearly same thing 81 times.
I would appreciate a detailed explanation about inner structure of for-loops in this circumstances.
Thank You,
Pavel Bykov

Accepted Answer

Matt J
Matt J on 15 Nov 2019
Undoubtedly, you meant to have
for i = 1:-0.1:0.9
for j = 1:-0.1:0.9
  2 Comments
Pavel Bykov
Pavel Bykov on 15 Nov 2019
Indeed, actually i meant 0.1:0.1:0.9. But same thing. I guess just too tired after 5 hours. Thank you very much!
Matt J
Matt J on 15 Nov 2019
Or maybe this
function M = meta2(obj)
p = obj.getParameters();
vals=0.9:0.1:1;
N=numel(vals);
for i = N:-1:1
for j = N:-1:1
p(3) = vals(i);
p(4) = vals(j);
M(i,j) = CModelDeficit(p);
end
end
end

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!