필터 지우기
필터 지우기

Replacing elements in matrix with relational operations

조회 수: 1 (최근 30일)
Feynman
Feynman 2013년 10월 7일
댓글: Walter Roberson 2013년 10월 7일
I am given a problem where I am given a matrix and I am suppose to change the values of the matrix depending on if a certain element of the matrix is greater than or less than a number. If it is greater than the variable n1 I am suppose to change the element to c1 and if is less than n1 I am suppose to change it to c2. I am to use only relational operations, I cannot use for, if, while or any implicit functions. How can I do this? This is what I have so far m3 is the matrix I am given
m4 = ((m3>n1)*c1)
m5 = ((m3<=n1)*c2)

채택된 답변

David Sanchez
David Sanchez 2013년 10월 7일
M=randi(10,3);
n1 = 5;
c1 = 4;
c2 = 3;
M1 = M<5;
D1 = c1*M1;
M2 = M>=5;
D2 = c2*M2;
new_M = D1 + D2;
% In a single line
new_M = c1*(M<5) + c2*(M>=5);
Adapt the values of n1, c1 and c4 to yours needs.
  댓글 수: 2
David Sanchez
David Sanchez 2013년 10월 7일
I meant to use n1 instead of its value:
% In a single line
new_M = c1*(M<n1) + c2*(M>=n1);
Walter Roberson
Walter Roberson 2013년 10월 7일
Addition is an implicit function in MATLAB: the method @double/plus will be called in this situation. Multiplication is also a function; I think @double/mtimes would be called for your code suggestion. Note that .* would be better than * in your code
Your code suggestion does not leave unchanged the parts of M that do not satisfy the conditions.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2013년 10월 7일
The task cannot be accomplished without using at least one implicit function other than the relational operators.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by