HELP : Subscript indices must either be real positive integers or logicals - AGAIN

I need your help to solve the problem of subscript index that must either be positive integer or logical. Can any one help to correct this ?
A = magic(5);
M1 = size(A,1);
M2 = size(A,2);
E = [5 8 20];
for x = 1:M1
for y = 1:M2
if A(A(x,y) == E)
A(x-1,y) = 5
end
end
end
Thank you!

 Accepted Answer

By including 'again' in the title I hope that you are learning from previous solutions and that this is a different type of cause to your previous such problems.
The line
A(x-1,y) = 5
fails first time round the loop because x is 1 so x-1 is 0 which is not a valid array index (this is what the error message tells you - it must be a real positive integer or a logical - 0 is neither of those).
How to fix it depends on your intent. Starting your for loop indexed from 2 instead of 1 would remove the error but may not be the solution you want.

6 Comments

@Adam,
I have another question. See the following code, first:
A = magic(5);
M1 = size(A,1);
M2 = size(A,2);
E = [5 20];
for x = 2:M1
for y = 2:M2
for k = 1:length(E)
if A(A(x,y) == E(k))
A(x-1,y) = E(k);
end
end
end
end
A
I can successfully modify the pixels values at (x-1,y) with reference to (x,y), according to the code provided above. Can you help/tell me how to modify the pixels also at (x+1,y), (x,y-1), and (x,y+ 1) - so that the output of A be equal to [17 5 1 8 15; 5 5 5 20 16; 4 5 20 20 20; 10 12 19 20 3; 11 18 25 2 9] or looks like shown below ?
17 5 1 8 15
5 5 5 20 16
4 5 20 20 20
10 12 19 20 3
11 18 25 2 9
You should just be able to add the equivalent lines of code to what you already have after
A(x-1,y) = E(k);
@Adam,
Thanks again but how exactly - so that I can achieve the above mentioned/expected result ?
for x = 2:(M1-1)
for y = 2:(M2-1)
for k = 1:length(E)
if A(A(x,y) == E(k))
A(x-1,y) = E(k);
A(x+1,y) = E(k);
A(x,y-1) = E(k);
A(x,y+1) = E(k);
end
end
end
end
should probably do the job, though I'm sure there are neater ways.
The above code did not unfortunately yield the results expected. See the results, it yielded:
A =
17 5 5 5 15
5 5 5 5 5
5 5 5 5 5
5 5 5 5 5
11 5 5 5 9
The expected results are shown below:
A =
17 5 1 8 15
5 5 5 20 16
4 5 20 20 20
10 12 19 20 3
11 18 25 2 9

Sign in to comment.

More Answers (0)

Asked:

on 11 Jan 2016

Commented:

on 13 Jan 2016

Community Treasure Hunt

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

Start Hunting!