필터 지우기
필터 지우기

main question: how to make function vectorized

조회 수: 1 (최근 30일)
yesenia Arzate-andujo
yesenia Arzate-andujo 2020년 4월 8일
답변: Ameer Hamza 2020년 4월 8일
Write a function with header [ans]=mychoice(a,b,operation). The input argument, operation, is a string that is either ‘ Add’,’Subtract’,’Multi’, or ‘Square’ and ans should be computed as a+b, a-b, a.*b, and a.^b for the respective values for operation. Be sure to make your function vectorized. Hint: Use the strcmp function.
a = [1 2 4 5]
b = [1 1 2 1]
this is what I have so far and I do not know how to run the code for me to input a and b
function [answer] = mychoice(a,b,myoperation)
addition = 'Add';
difference = 'Subtract';
product = 'Multi';
square = 'Square';
if strcmp(myoperation,addition)
answer = a + b;
elseif strcmp(myoperation,difference)
answer = a - b;
elseif strcmp(myoperation,product)
answer = a .* b;
elseif strcmp(myoperation,square)
answer = a .^ b;
else
fprintf('Invalid Operation, check your input\n');
end

답변 (1개)

Ameer Hamza
Ameer Hamza 2020년 4월 8일
Vectorization means that the function should be able to accept arrays and apply an operation on all of its elements. In that sense, your function is already vectorized. You need to call the function like this in the command window
a = [1 2 4 5];
b = [1 1 2 1];
mychoice(a,b,'Subtract')

카테고리

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