# How to rewrite my code without loops?

2 views (last 30 days)
Valeri Aronov on 22 Aug 2021
Commented: Valeri Aronov on 22 Aug 2021
How to rewrite this code without loops:
for i=1:length(x)
for j=1:length(f)
end
end
Thanks.

Walter Roberson on 22 Aug 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.
2 4 6 8 10 3 6 9 12 15 4 8 12 16 20
dev = [-2 3 -4 5 -6]
dev = 1×5
-2 3 -4 5 -6
x = randi(9, 1, size(GradW,1)) %contents not actually used, but shape is
x = 1×3
1 4 3
f = randi(9, 1, size(GradW,2)) %contents not actuall yused, but length is
f = 1×5
8 9 6 8 7
-72 -108 -144
for i=1:length(x)
for j=1:length(f)
end
end
-72 -108 -144
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)
Valeri Aronov on 22 Aug 2021
Right.
1) length(x) was there because the lengths of multiple other arrays were deduced from length(x). You are certainly right: using length(dev) here makes for more robust code.
2) similarly it is better to use length(GradW(:,1)) instead of length(f). My motivation was the same as in 1)
3) regardless of 1)-2) your suggested code:
does exactly what I want. I knew that you will come up with something strikingly simple ofr my case. Thanks.

R2021a

### Community Treasure Hunt

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

Start Hunting!