Reputation: 49
I need to compare a value in a multidimentional array and according to this comparison, I need to assign a value of another matrix in the same index to a new matrix of the same size in the same index. Can you give me an idea on how to do this?
Here's the code below using the for loop, but I need to do this without using a for loop.
for i = 1:sizeOfMatrix(1, 1)
for j = 1:sizeOfMatrix(1, 2)
if grayImage(i, j) > t
result(i, j) = 0;
else
result(i, j) = grayImage(i, j);
end
end
end
where t is the value that I need to compare with.
Upvotes: 0
Views: 119
Reputation: 2652
Use logical indexing:
result = zeros(size(grayImage));
result(grayImage <= t) = grayImage(grayImage <= t);
This is a much faster and cleaner way to access matrix elements conditionally.
Alternatively, you can do:
result = grayImage;
result(grayImage > t) = 0;
Upvotes: 1