MATLAB Answers

How do I replace Matrix elements

201 views (last 30 days)
Liam Bouchereau
Liam Bouchereau on 27 Oct 2020
Edited: Stephen on 27 Oct 2020
Given a matrix A replace elements not equal 0 and not equal 1 by 5. Use disp() function to print out the resulting array.
So far I've got
A(A~=0) = 5;
disp(A);
but do not know how to make it 0 AND 1.
  2 Comments
Liam Bouchereau
Liam Bouchereau on 27 Oct 2020
Yeah so all elements that don't = 1 or 0 need to be replaced by the element 5

Sign in to comment.

Accepted Answer

Sudhakar Shinde
Sudhakar Shinde on 27 Oct 2020
Edited: Sudhakar Shinde on 27 Oct 2020
Try this:
A((A>1)|(A<0))=5
  5 Comments

Sign in to comment.

More Answers (1)

Stephen
Stephen on 27 Oct 2020
Edited: Stephen on 27 Oct 2020
Use AND instead of OR:
>> A = [-1,0,4,6;1,1,0,2;-7,0,5,0;5,1,5,1]
A =
-1 0 4 6
1 1 0 2
-7 0 5 0
5 1 5 1
>> A(A~=0&A~=1) = 5
A =
5 0 5 5
1 1 0 5
5 0 5 0
5 1 5 1

Tags

Products

Community Treasure Hunt

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

Start Hunting!