Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

How to subtract from a vector array and, if the answer is lees than 0, have it return a value of 0

조회 수: 2 (최근 30일)
I'm trying to subtract a number from a specific value in a vector. Then, if the answer is less than 0, I want it to return the answer with it being rounded to 0.
this is what I meam
%example%
x = [1 2 3]
x(1)-2
%the result would look like this%
x =
-1 2 3
%but I want it to look like this%
x =
0 2 3
How do I do this without using conditionals?

답변 (2개)

David Hill
David Hill 2020년 9월 15일
x=[1 2 3];
x=x-2;
x(x<0)=0;
  댓글 수: 2
Brett Baxter
Brett Baxter 2020년 9월 15일
Thank you, but now I need the function to tell me by how much it goes under if and when it does. I essentially need to write a function like this:
x=[1, 2 3]
y= 2
x(1) - y
if x(1)<0
totalsubtracted = y +x(1)
else
totalsubtracted = x(1)-y
end
But without conditionals. How do I do this?
David Hill
David Hill 2020년 9월 15일
x=[1 2 3];
amountbelowzero=zeros(size(x));
x=x-2;
amountbelowzero(x<0)=abs(x(x<0));
x(x<0)=0;

John D'Errico
John D'Errico 2020년 9월 15일
편집: John D'Errico 2020년 9월 15일
Simple. No need to test anything either. Just use the max function.
x = [1 2 3];
x(1) = max(x(1) - 2,0);
x
x =
0 2 3

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by