How to rewrite my code without loops?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Valeri Aronov
el 22 de Ag. de 2021
Comentada: Valeri Aronov
el 22 de Ag. de 2021
How to rewrite this code without loops:
Grad = zeros(size(x));
for i=1:length(x)
for j=1:length(f)
Grad(i) = Grad(i) + 2*GradW(i,j).*dev(j);
end
end
Thanks.
0 comentarios
Respuesta aceptada
Walter Roberson
el 22 de Ag. de 2021
lenth(f) has no obvious relationship to any of the rest of the code. Is f shorter than dev is so you are only wanting to do a subset of dev ? If you are wanting all of dev then use the number of elements in dev, not the number in f.
You initialize Grad to size(x) but you only iterate i as the length(x) not as the number of elements in x.
It is not obvious that length(x) or size(x) is related to the size of GradW or dev.
GradW = (1:5).*(2:4).'
dev = [-2 3 -4 5 -6]
x = randi(9, 1, size(GradW,1)) %contents not actually used, but shape is
f = randi(9, 1, size(GradW,2)) %contents not actuall yused, but length is
answer1 = reshape(2*GradW * dev(:), size(x))
Grad = zeros(size(x));
for i=1:length(x)
for j=1:length(f)
Grad(i) = Grad(i) + 2*GradW(i,j).*dev(j);
end
end
answer2 = Grad
You can see the probable simple formula at answer1, but because your sizes are not related to the variables you calculate on, we cannot be sure.
It seems odd to want to force the answer to be the shape of x; it would make more sense to let it be a column vector (in which case skip the reshape() of answer1)
Más respuestas (0)
Ver también
Categorías
Más información sobre Language Support en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!