필터 지우기
필터 지우기

How do I replace certain values of a vector A that are greater than certain values of a vector B for the values this vector?

조회 수: 4 (최근 30일)
My problem is the following: I have a matrix A(x,y) that some of it values are greater than a vector B(x) that sets a limit of amplitude. I want to replace the values of A that are greater than the values of B for the respective values of B. I tried this code but without succsess:
for ii = 1:size(A,1)
A(A(ii,:) > B(ii)) = B(ii);
end
Any clarification will help a lot! Thanks in advance.

채택된 답변

Adam Danz
Adam Danz 2018년 8월 23일
Here's a solution with fake data that match the dimensions in your question (an earlier answer by me, now deleted, used a vector instead of a matrix for A).
% fake data
A = [ 9 2 3; 4 5 6; 1 1 8];
B = [2;3;9];
%replicate B to match A
Br = repmat(B, 1, size(A,2));
%Replace values in A that exceed vals in B
A(A>Br) = Br(A>Br);
  댓글 수: 1
Adam Danz
Adam Danz 2018년 8월 23일
편집: Adam Danz 2018년 8월 23일
Note that this solution (and Stephen's) takes care of the whole matrix at once. It looks like you're doing this in a loop which will require adaptation if you decide to keep the loop. Stephen's bsxfun solution is higher level and is unnoticeably slower (microseconds) than mine. If you're looking for a 1-liner, use Stephen's solution.

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

추가 답변 (2개)

Stephen23
Stephen23 2018년 8월 23일
편집: Stephen23 2018년 8월 23일
>> A = [9,2,3;4,5,6;1,1,8];
>> B = [2;3;9];
Method ONE: for MATLAB versions R2016b+ with implicit scalar expansion, all you need is:
>> min(A,B)
ans =
2 2 2
3 3 3
1 1 8
For older versions try the two following methods.
Method TWO: repmat with min:
>> min(A,repmat(B,1,3))
ans =
2 2 2
3 3 3
1 1 8
Method THREE: Use min with bsxfun:
>> bsxfun(@min,A,B)
ans =
2 2 2
3 3 3
1 1 8

Matheus Henrique Fessel
Matheus Henrique Fessel 2018년 8월 23일
Thank you so much, gentlemen! You were very helpful and both suggestions work perfectly!

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by