How can I compare all row in a column with a value and replace it?

4 views (last 30 days)
Hello
I want to compare all row in one column with a value, and if one of them being larger than value, I want replace it with value.
How can I do this with if statement or any other way ?
if(path(1,:)>value)
? ???

Accepted Answer

Walter Roberson
Walter Roberson on 17 Jun 2015
is_greater = path(1,:) > value;
Now if you want to replace the entire column with the value then:
if any(is_greater)
path(1,:) = value;
end
If you want to replace only the locations then
path(1,is_greater) = value;
However, there is another way for the situation where you want to take the current item provided it is not greater than value, and value otherwise: you can use
path(1,:) = min(path(1,:), value);
and you can do the entire array at once with
path = min(path, value);
When you use min() the replacement is always the cutoff value. When you use the logical indexing I showed, the replacement could be arbitrary, such as
path(1,is_greater) = 0;

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!