We are creating a function that takes 2 vectors, x and N, where x contains the values and N contains the number of times each value in x appears. We want to find the average of the values in x.
% this function is written and saved in a script file
%function avg = myavg(x,N)
%sizex = size(x); % recall these return 2 values, we want the 2nd value
%sizeN = size(n);
%if(sizex(2) ~= sizeN(2))
%beep
%disp('Error: number of elements does not match!')
%else
%total = sum(N); % total # of elements
%s = x.*N; % element-by-element multiplication
%avg = sum(s)/total;
%end
%end
x = [12 5 34 87 35 90 124];
N = [2 4 56 12 6 9 14];
myavg(x,N)
ans = 55.8058
% the following function is written and saved to a script file
% function output = poly(x)
% output = 1234*x.^3-43388*x.^2+531*x-123;
% end
% now we can solve lengthy and complicated polynomials quickly
poly(45)
ans = 24611322
% this extends to using matrices as well
poly([1 2; 3 4])
ans = -41746 -162741 -355704 -613231
This function will take user input to calculate the area. In order to accomplish this, we need to use the input() function.
% example usage of input()
a = input('Enter the value for a: ')
% Jupyter notebook doesnt allow for user input
% the result in a MATLAB command window is:
% Enter the value for a: 4
% a =
% 4
% providing matrices will also work
% we can also read strings
Name = input('What is your name: ','s')
% Here is the code for calculating area of triangle with user input
b = input('Enter the value for the base: ');
h = input('Enter the value for the height: ');
area = 0.5 * b * h;
disp(['The value for area is: ' num2str(area)])