Multiplying elements of a vector

조회 수: 34 (최근 30일)
Stephen Warren
Stephen Warren 2020년 6월 28일
편집: madhan ravi 2020년 6월 28일
I'm creating a function to find areas of shapes. It takes two inputs, the first is a vector and the second is a variable number.
function area = area_calculator(A, num)
switch num
case 1 % Circle
r = norm(A);
A = pi*r^2 % Area
case 2 % Rectangle
A = b*h % Area; I want to multiply vector element 1 by vector element 2
end
So if I give it
>> area_calculator([2,4], 2)
I'm wanting b*h to be 2*4
I'm unsure how to instruct matlab to perform multiplication within the vector
Thank you very much

채택된 답변

madhan ravi
madhan ravi 2020년 6월 28일
편집: madhan ravi 2020년 6월 28일
Use prod() to perform multiplication within a vector.
function area = area_calculator(vector, num)
switch num
case 1 % Circle
r = norm(vector);
area = pi*r^2 % Area
case 2 % Rectangle
area = prod(vector);% or you can use vector(1)*vector(2) % Area; I want to multiply vector element 1 by vector element 2
end

추가 답변 (1개)

per isakson
per isakson 2020년 6월 28일
Replace
case num == 1
by
case 1
  댓글 수: 1
Stephen Warren
Stephen Warren 2020년 6월 28일
Thanks, that makes it cleaner.
How do I perform multiplication of elements from within one vector

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by