'How can I convert jpg file to pbm file through only matrix operation?

I have tried the method as follows, but it didn't work so efficient.

for i = 1:h 
            for j = 1:w 
                Img(1,(i-1)*aligned_w+j) = (Matrix(i,j)&1);
                %fwrite(file,1-Matrix(i,j),'ubit1');
            end
            for j = 1:align
                %fwrite(file,0,'ubit1');
                Img(1,(i-1)*aligned_w+w+j)=0;
            end
        end
        fwrite(file,Img,'ubit1');

the result of above code is off track compared to the imwrite(imread('.jpg','jpg'),'.pbm','pbm'), can anyone tell me how to solve it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source