MATLAB - Data is lost when closing the FOR loop

Asked

Viewed 62 times

2

I’m having trouble with a loop loop that counts the white pixels of a piece of an image and stores the position x and y of the piece and the total of white pixels. When printing the values within the loop it works, but immediately after the loop the three arrays are zeroed. Can someone help me?

Code:

y = zeros(altura*largura);
x = zeros(altura*largura);
v = zeros(altura*largura);


for j=0:altura-1
    for k=0:largura-1

        pedaco = f8(j*40+1 : j*40+40, k*40+1 : k*40+40); %binary piece
        pedac = im2uint8(pedaco);
        totalBrancos = sum(sum(pedac)); %sum white pixels

        pos = altura*j+k+1;

        y(pos) = j;
        x(pos) = k;
        v(pos) = totalBrancos;

        disp(y(pos)); %works
        disp(x(pos)); %works
        disp(v(pos)); %works

    end
end  

disp(y); %all zeros
disp(x); %all zeros
disp(v); %all zeros
  • The code is just that?

  • This piece of code is part of a larger code.. but the part that does what I mentioned "a loop that counts the white pixels of a piece of an image and stores the x and y position of the piece and the total white pixels", is all there.

  • strange, it doesn’t make sense that the data is zeroed when leaving the loop, is sure that there is no more code ?

  • exactly @ederwander. I don’t understand why this happens. As I said before, the part that counts the white pixels and stores the positions x and y and the total, is this.

2 answers

0

I guess they’re not all zeroes.

In the first three lines, try to do so:

y = zeros(altura*largura,1);
x = zeros(altura*largura,1);
v = zeros(altura*largura,1);

And then test the program again

0

The answer given by Tied --alias, I think not all elements will be zero also-- works for if you want to put all points on a line, if the intention is to leave all points on a matrix, the code changes at some points:

In the statement:

y = zeros(altura,largura);
x = zeros(altura,largura);
v = zeros(altura,largura);

Inside the loop:

    y(j+1,k+1) = j;
    x(j+1,k+1) = k;
    v(j+1,k+1) = totalBrancos;

    disp(y(j+1,k+1)); %works

Note that in this case, the matrices y and x end up with the value of its respective index by subtracting 1.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.