Matlab: How to write a function that gets an integer n and always returns the result P = 1*1.2*1.4*....*(1+0.2*(n-1)) - matlab

I am trying to solve a problem that requires writing a function called repeat_prod(n), that gets an integer n and returns the result of the following function:
P = 1*1.2*1.4*....(1+0.2(n-1))
for exemple if n is 6:
repeat_prod(6)
ans = 9.6768
I tried the following:
function P = repeat_prod(n)
for 1:n-1
P = (1+0.2*(n-1));
end
end
But it does not run. How can I get the loop to work?

The logic within your function should be something like below
function P = repeat_prod(n)
P = 1; % initial value for following cumulative products
for k = 1:n
P = P*(1+0.2*(k-1));
end
end
Compact Version
You can also use prod within your function repeat_prod to replace for loop, i.e.,
function P = repeat_prod(n)
P = prod(1 + 0.2*((1:n)-1));
end

Related

Why does this not correctly evaluate e^x using the Taylor series?

I am attempting to write a function called expSeries which uses another function factFunc to evaluate e^x. I have already written the function factFunc, as shown below:
function fact = factFunc(n)
f = 1;
for a = 1:b
f = f*a;
end
fact = f;
end
I am now attempting to write the function expSeries which evaulates e^x using the Taylor series. This is what I have so far:
function expo = exponentialFunc(x)
terms = input('Enter the number of terms');
b = 0;
for i = 1:terms
b = x/factFunc(terms);
end
expo = b;
end
And in the main program, I have
n = exponentialFunc(4);
disp(n);
Where in this instance I am trying to find e^4. However, the output is not what expected. Does anyone have any idea where I am going wrong?
Fix to factFunc:
function fact = factFunc(n)
f = 1;
for a = 1:n
f = f*a;
end
fact = f;
end
Fix to exponentialFunc
function expo = exponentialFunc(x)
terms = input('Enter the number of terms');
b = 0;
for i = 0:terms-1
b = b + x^i/factFunc(i);
end
expo = b;
end
Example
>> exponentialFunc(4)
Enter the number of terms10
ans =
54.1541
Note exp(4) = 54.59815...

How to calculate the expected value of a function with random normally distributed X?

I am trying to calculate on MatLab the Expectation for the function e^X where X ~ N(mu,sigma^2). In my example, mu = 0 and sigma = 1.
function [E] = expectedval(m,s)
%find E(e^x) with X~N(mu,sigma)
% mu = 0 , sigma = 1
X = normrnd(m,s);
f=exp(X);
mean(f)
So by the end I can run expectedval(0,1) to get my solution. The code runs with no issue, but I would like to compile a histogram to analyse the data with several runs. How may I collect this data with some sort of loop?
I'd appreciate any improvement ideas or suggestions!
Actually, your function just creates one random value for the given mean and variance... so there's actually no point in calculating a mean. On the top of that, the output E value is not assigned before the function finishes. The function can therefore be rewritten as follows:
function E = expectedval(m,s)
X = normrnd(m,s);
E = exp(X);
end
If you want to draw a sample from the normal distribution, and use the mean to compute the correct expected value, you can rewrite it as follows instead:
function E = expectedval(m,s,n)
X = normrnd(m,s,[n 1]);
f = exp(X);
E = mean(f);
end
And here is an example on how to run your function many times with different parameters, collecting the output on each iteration:
m = 0:4;
m_len = numel(m);
s = 1:0.25:2;
s_len = numel(s);
n = 100;
data = NaN(m_len*s_len,1);
data_off = 1;
for s = 1:s_len
for m = 1:m_len
data(data_off) = expectedval(m,s,n);
data_off = data_off + 1;
end
end

I want to feed in a function handle into a matlab function I made

I am trying to feed a function handle into the function I created below. I'm not exactly sure how to do this.
For example, how do I get:
conjugate_gradient(#(y) ABC(y), column_vector, initial_guess)
to not error?
If I use matlab's pcg function in the same way it will work:
pcg(#(y) ABC(y),b,tol).
I tried reading the pcg function, and they do take about this in the function description, however I'm still super inexperienced with MATLAB and had shall we say some difficulty understanding what they did.Thank You!
function [x] = conjugate_gradient(matrix, column_vector, initial_guess)
y = [];
col_size = length(column_vector);
temp = size(matrix);
mat_row_len = temp(2);
% algorithm:
r_cur = column_vector - matrix * initial_guess;
p = r_cur;
k = 0;
x_approx = initial_guess;
for i=1:mat_row_len
alpha = ( r_cur.' * r_cur ) / (p.' *(matrix* p));
x_approx = x_approx + alpha * p;
r_next = r_cur - alpha*(matrix * p);
fprintf(num2str(r_next'*r_next), num2str(i))
y = [y; i, r_next'*r_next];
%exit condition
if sqrt(r_next'*r_next) < 1e-2
y
break;
end
beta = (r_next.'* r_next )/(r_cur.' * (r_cur) );
p = r_next + beta * p;
k = k+1;
r_cur = r_next;
end
y
[x] = x_approx;
end
When you do
f = #(y) ABC(y)
You create a function handle. (Note that in this case it's the same as f=#ABC). This handle is a variable, and this can be passed to a function, but is otherwise the same as the function. Thus:
f(1)
is the same as calling
ABC(1)
You pass this handle to a function as the first argument, which you have called matrix. This seems misleading, as the variable matrix will now be a function handle, not a matrix. Inside your function you can do matrix(y) and evaluate the function for y.
However, reading your function, it seems that you treat the matrix input as an actual matrix. This is why you get errors. You cannot multiply it by a vector and expect a result!

Trying to get a MATLAB function to take an array of inputs

I'm trying to call a numerical integration function (namely one that uses the trapazoidal method) to compute a definite integral. However, I want to pass more than one value of 'n' to the following function,
function I = traprule(f, a, b, n)
if ~isa(f, 'function_handle')
error('Your first argument was not a function handle')
end
h = (b-a)./ n;
x = a:h:b;
S = 0;
for j = 2:n
S = S + f(x(j));
end
I = (h/2)*(f(a) + 2*S + f(b)); %computes indefinite integral
end
I'm using; f = #(x) 1/x, a = 1 and b = 2. I'm trying to pass n = 10.^(1:10) too, however, I get the following output for I when I do so,
I =
Columns 1 through 3
0.693771403175428 0.069377140317543 0.006937714031754
Columns 4 through 6
0.000693771403175 0.000069377140318 0.000006937714032
Columns 7 through 9
0.000000693771403 0.000000069377140 0.000000006937714
Column 10
0.000000000693771
Any ideas on how to get the function to take n = 10.^(1:10) so I get an output something like,
I = 0.693771403175428, 0.693153430481824, 0.693147243059937 ... and so on for increasing powers of 10?
In the script where you are calling this from, simply iterate over n
k = 3;
f = #(x)1./x;
a = 1; b = 2;
I = zeros(k,1);
for n = 1:k
I(n) = traprule(f, a, b, 10^n);
end
% output: I = 0.693771403175428
% 0.693153430481824
% 0.693147243059937
Then I will contain all of the outputs. Alternatively you can adapt your function to use the same logic to loop over the elements of n if it is passed
as a vector.
Note, you can improve the efficiency of your traprule code by removing the for loop:
% This loop operates on every element of x individually, and is inefficient
S = 0;
for j = 2:n
S = S + f(x(j));
end
% If you ensure you use element-wise equations like f=#(x)1./x instead of f=#(x)1/x
% Then you can use this alternative:
S = sum(f(x(2:n)));

Error while calculating limit - Conversion to logic from syms is not possible - MATLAB -2014a

I want to calculate the limit of log(CR(r))/log(r) as r tends to 0.
MATLAB code is written below.
function cd = CD(data)
syms r
cd = limit(log(CR(r,data))/log(r),r,0) ;
end
function val = hf(xi,xj,r)
dis = abs(xi-xj);
if(dis <= r)
val = 1;
else
val = 0 ;
end
end
function cr = CR(r,data)
N = length(data);
sum = 0;
for i = 1 : N
for j = i+1 : N
sum = sum + hf(data(i),data(j),r);
end
end
cr = sum/(N*(N-1));
end
Error:-
Well, the error message says it all really:
You can't use a symbolic variable in an equality check. How can you know if dis <= r when r doesn't have a value?
I'm obligated to say this:
Don't use sum as a variable name! It's a very important and useful builtin function. You're making it useless when doing that.
i and j are bad variable names in MATLAB, since they denote the imaginary unit (sqrt(-1)).
Also, did I remember to say: Dont use sum as a variable name!
PS! Your hf-function is equivalent to:
function val = hf(xi,xj,r)
var = abs(xi-xj) <= r; % Still doesn't work since r is symbolic
end