For and While loops
2 个评论
Hi @Zahraa Al-Waeli,
To illustrate it by example code snippet, I will first load an example image using the imread function, then extract the number of rows and columns in the image using the size function. Next, use nested "for" loops to iterate through each pixel of the image. The outer loop (for i = 1:rows) iterates over the rows, while the inner loop (for j = 1:cols) iterates over the columns. Within the nested loops, I will access the pixel value at position (i, j) in the image matrix using img(i, j).
You can perform various operations on the pixel values inside the loop, such as displaying the pixel values, modifying them, or analyzing them. Here is example code snippet,
% Read and display the image
img = imread('/MATLAB Drive/IMG_7236.jpg');
% Get the size of the image (rows and columns)
[rows, cols, ~] = size(img);
% Nested for loops to scan through each pixel
for i = 1:rows
for j = 1:cols
% Access pixel values at position (i, j)
pixel_value = img(i, j);
% Perform operations on the pixel value (e.g., display, modify, analyze)
disp(['Pixel value at position (', num2str(i), ',', num2str(j), '): ', num2str(pixel_value)]);
end
end
Please see attached results.

Please let us know if you have any further questions.
回答(1 个)
- https://www.mathworks.com/help/releases/R2023b/matlab/ref/for.html?searchHighlight=for&s_tid=doc_srchtitle
- https://www.mathworks.com/help/releases/R2023b/matlab/ref/while.html?searchHighlight=while&s_tid=doc_srchtitle
- https://www.mathworks.com/help/releases/R2023b/matlab/ref/imread.html?searchHighlight=imread&s_tid=doc_srchtitle
- https://www.mathworks.com/help/releases/R2023b/matlab/ref/imshow.html?searchHighlight=imshow&s_tid=doc_srchtitle
- https://www.mathworks.com/help/releases/R2023b/matlab/ref/size.html?searchHighlight=size&s_tid=doc_srchtitle
- https://www.mathworks.com/help/releases/R2023b/matlab/ref/rgb2gray.html?searchHighlight=rgb2gray&s_tid=doc_srchtitle
0 个评论
另请参阅
类别
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!