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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by