Index in position 1 is invalid. Array indices must be positive integers or logical values.
Show older comments
function findalph = impGradDes(M, P)
[n, m, d] = size(M);
%% Initializing the optimal weight vector
findalph = ones(d,1);
%% Optimization process
for i=1:d
for j=1:d
A(i,j) = sum(sum(M(:,:,i).*M(:,:,j)));
end
B(i,1) = sum(sum(P.*M(:,:,i)));
end
tau = 5;
iter = 150000;
gamma1 = 1/200000;
gamma2 = 1;
inv = (eye(d) + 2*tau*gamma1*A)^(-1);
for i = 1:iter
findalph = inv * (findalph+2*tau*max(-findalph,0)+2*tau*gamma1*B);
end
end
4 Comments
dpb
on 20 Jun 2019
Include all the error message in context of the code that generated it.
How are we supposed to guess even which code is generating the error -- altho doesn't look on quick perusal this code would.
The last for loop is pointless--there's nothing in the loop dependent upon the loop variable i
"The last for loop is pointless--there's nothing in the loop dependent upon the loop variable i"
Not necessarily pointless: each iteration's findalph value uses the previous iteration's findalph value, which is a perfectly valid, non-pointless construct (whether it is correctly used in this situation is another question entirely). It is not required to use the loop variable in order for a for loop to be useful, a for loop simply repeats some code a set number of times... whether it is pointless or not depends on what the code does, not only on the usage of the loop variable.
A simple demonstration of this, that calculates the exponent of matrix values:
>> N = 5;
>> M = randi(9,5,3)
M =
9 5 8
6 8 5
6 4 7
8 1 8
2 2 2
>> Z = M;
>> for k = 2:N, Z = Z.*M; end, Z % k is NOT used!
Z =
59049 3125 32768
7776 32768 3125
7776 1024 16807
32768 1 32768
32 32 32
>> M.^N % for comparison
ans =
59049 3125 32768
7776 32768 3125
7776 1024 16807
32768 1 32768
32 32 32
ACHALA SHAKYA
on 20 Jun 2019
dpb
on 20 Jun 2019
Yeah, I missed seeing the LHS variable also being on RHS, Stephen...
Answers (1)
Bjorn Gustavsson
on 20 Jun 2019
OK, when you have a problem that simple (in terms of figuring out what is going on) you do this:
dbstop if error
Then rerun the code, matlab will then stop at the offending line and you get a prompt at that line making it possible for you to inspect the variables to see what's going on. Presumably something strange is happening with either i or j, so you
can just check those variable and the M and P variables too.
HTH
Categories
Find more on Choose a Solver in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!