first time user syntax help

edited May 2011 in Science & Tech
Hey, I have a 2048x2048 matrix with values of either 0 or 1 which is called "white". I need to find the total number of 3x3 blocks in the matrix where each data point has a value of 1, ie,

1 1 1
1 1 1
1 1 1

Im a first time user and I think that my problem is syntax. My code is as follows,

x=0

for i=2:2047 j=2:2047

if white(i-1,j-1)==1 & white(i-1,j)==1 & white(i-1,j+1)==1 & white(i,j-1)==1 & white(i,j)==1 & white(i,j+1)==1 & white(i+1,j-1)==1 & white(i+1,j)==1 & white(i+1,j+1)==1

x=x+1

end

y=sum(x)

end

Ive been at it for a few hours and any help would be really appreciated. Ill be spending the rest of the afternoon trying to solve this problem....

Thanks for your help!

Comments

  • drasnordrasnor Starship Operator Hawthorne, CA Icrontian
    edited May 2011
    To loop through two variables you need a nested loop. The structure for that looks like:[php]for i=1:10
    for j=1:10
    things = do(stuff);
    end
    end[/php]As an aside, 'x' is only a single element so y = sum(x) will always be equal to x.
  • kryystkryyst Ontario, Canada
    edited May 2011
    Just setting aside that your initial syntax is wrong. From a logical side it just wouldn't work either because as you have it, it would increment i & j equally. Meaning you'd only go through your grid on a diagonal so you'd be checking:

    2:2, 3:3, 4:4 etc.... You'd miss situations like 2:3, 2:4 etc....

    That's why you need to do it in 2 loops just from a basic logical reason.

    Also if you have a grid thats is 2048x2048 you don't need to do a loop that goes from 1-2048 you only need to loop from 1-2046 because if you are checking a 3x3 grid then you don't need to do a check when you are on the 2nd from the last outer edges.
  • drasnordrasnor Starship Operator Hawthorne, CA Icrontian
    edited May 2011
    C'mon kryyst, you know as well as I do that MATLAB array indices are from 1 to n, not 0 to n-1. He's got it right.
  • kryystkryyst Ontario, Canada
    edited May 2011
    You know I read that three times last night and never noticed that he was going from 2-2047 in his loop. I'm guess that's why I probably stop myself from trying to code any of my own things past 3 beers and 10pm.
Sign In or Register to comment.