필터 지우기
필터 지우기

Element by Element Subtraction

조회 수: 125 (최근 30일)
Sanim Rahman
Sanim Rahman 2017년 12월 10일
댓글: anuforo peter 2020년 3월 7일
I am trying to do element by element subtraction like the following:
a= [1,2,3,4,5] b= [-1,-2,-3]
I would like my output to be "a" to be subtracted by the first element of "b" then by the second element and so on. The output "c" should look like: c=[2,3,4,5,6,3,4,5,6,7...]
I understand that if I simply do "c=a-b" will not work because the dimensions do not agree. Would something like this require a loop?

채택된 답변

Image Analyst
Image Analyst 2017년 12월 10일
Try this:
a= [1,2,3,4,5]
b= [-1,-2,-3]
c = a' - b;
c = c(:)'
You get
c =
2 3 4 5 6 3 4 5 6 7 4 5 6 7 8
in R2016b (I believe) or later that has automatic expansion capability.
  댓글 수: 3
anuforo peter
anuforo peter 2020년 3월 7일
What about doing this on a mutidimensional array
anuforo peter
anuforo peter 2020년 3월 7일
Please help! Thank you ?

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

추가 답변 (1개)

Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan 2017년 12월 10일
minus operator in Matlab can inherently handle this, so you don't need a loop. Checkout >> help minus. For your case, something like this will work.
a= [1,2,3,4,5]; b= [-1,-2,-3];
c = reshape(a'-b,1,numel(a)*numel(b));

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by