main question: how to make function vectorized
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
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')
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!