0

If I generated a random 5-by-5 matrix using the code r = rand(5). I would like to find the location of the max value and replace this value by 10, and the min value and replace the value by -10.

How can I do it?

i tried to do the following:

r=rand(5)
find(max(max(r)))

Will this line give me the correct location of max value? And if it was correct now how can I replace the value by 10?

Steve
  • 1,579
  • 10
  • 23
user3620862
  • 53
  • 1
  • 3
  • 5

2 Answers2

2
r = rand(5);
maxr = max(r(:));%//get maximum
r(r==maxr) = 10; %// replace maximum with 10

Use logical indexing to replace the maximum value with 10.

Community
  • 1
  • 1
Adriaan
  • 17,741
  • 7
  • 42
  • 75
2

max returns two output arguments, first the value and then the index. Using (:) to convert your matrix to a vector and linear indexing to access, you can use this code:

[value,index]=max(r(:));
r(index)=10;
Daniel
  • 36,610
  • 3
  • 36
  • 69