Create an array of handle objects using for-loop

3 visualizaciones (últimos 30 días)
Pavel Bykov
Pavel Bykov el 15 de Nov. de 2019
Comentada: Matt J el 15 de Nov. de 2019
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

Respuesta aceptada

Matt J
Matt J el 15 de Nov. de 2019
Undoubtedly, you meant to have
for i = 1:-0.1:0.9
for j = 1:-0.1:0.9
  2 comentarios
Pavel Bykov
Pavel Bykov el 15 de Nov. de 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 el 15 de Nov. de 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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by