MATLAB Answers

Looping vector values into functions

3 views (last 30 days)
JR
JR on 14 Nov 2020
Answered: Athul Prakash on 17 Nov 2020
So for the following code, my goal is to evaluate each value within the vector "n" in the last 2 functions and spit out a vector that has each "n" value's respective answer.
I also, within the function, need to evaluate "h" values for each "n" value based on the respective equation.
I am not sure how to code it so that matlab takes in each value within the vector and not each individual value between n1 and n12 because thats way too many numbers to loop through.
I have highlighted the codes of interest. Any help is greatly appreciated!
%% "n" value and respective "h" value (step-size)
x0=0;
x1=2;
n1=2^1;
n2=2^2;
n3=2^3;
n4=2^4;
n5=2^5;
n6=2^6;
n7=2^7;
n8=2^8;
n9=2^9;
n10=2^10;
n11=2^11;
n12=2^12;
n=[n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 n11 n12];
for i=n1:
h=(x1-x0)./n(i);
end
%h=(x1-x0)/n2;
%% Computation of integral estimation with respective method for each "n"
LE=leftendpoint(n2,h);
trap=trapmethod(n2,h);
%% Function to determine f(x) at any "x" value
function y=funcvalue(x)
y=(x)*(exp(x^2/4));
end
%% Left end-point integral estimation function
function LE=leftendpoint(n2,h)
f_x= @(x) (x).*(exp(x.^2./4));
x0=0;
x1=2;
xk_values=linspace(h,(n2*h)-h,n2-1);
a1=f_x(xk_values);
b1=sum(a1);
LE=h*b1;
end
%% Trapezoid integral estimation function
function trap=trapmethod(n2,h)
f_x= @(x) (x).*(exp(x.^2./4));
x0=0;
x1=2;
xk_values=linspace(h,(n2*h)-h,n2-1);
a=f_x(xk_values);
b=sum(a);
trap=h*((((f_x(x0)+f_x(x1))/2))+b);
end

Answers (1)

Athul Prakash
Athul Prakash on 17 Nov 2020
Saving multiple variables with names 'n1', 'n2', etc may be a bad practice, I would recommend using a vector 'n' with indices 1-12 instead.
You may find vector operations much cleaner for your purpose, for example -
You may replace the top part of the code with
n = 2.^[1:12];
% instead of for loop :-
H_vec = (x1-x0)./n;
Once you pick up the habit of vectorizing operations wherever possible, you may rework the code suitably.
You can checkout these links to pick up vectorization:
2) Sections 5,6,12 in Matlab OnRamp online course may be useful
https://www.mathworks.com/help/matlab/matlab_prog/vectorization.html#:~:text=MATLAB%C2%AE%20is%20optimized%20for,vector%20operations%20is%20called%20vectorization.

Community Treasure Hunt

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

Start Hunting!