[Octave]Trouble visualising how to write a row vector of exponents - matlab

as the title states, I was following a guideline on coding a polynomial regression function but I am currently stuck on what it means to write a row vector of exponents. I need to initialise two variables, one being 'vector1', a column vector of a variable 'X', and 'vector2' which is meant to be a row vector of exponents from 1 to 'p'. Once that's done, I'm supposed to fill it in the bsxfun as such "X_poly = bsxfun(#power, vector1, vector2)".
Now the problem arises when I try to write in vector2. I have trouble visualising how to write this code. I've tried "vector2 = X(1:p,:)", "vector2 = X*p", "vector2 = X'(1:p,:)". Obviously none of these worked and I just feel this strong sense of defeat everytime I get it wrong. I've tried googling but the results have yielded no fruition.
I feel very lost and I'm grasping at straws at this point.

You don't need to use bsxfun here, the power function (and its equivalent operator .^) is vectorised (i.e. it can accept arrays process them in an element-wise manner).
octave:1> v1 = 1:10;
octave:2> v2 = 1:10;
octave:3> v1 .^ v2
ans =
1 4 27 256 3125 46656 8.2354e+05 1.6777e+07 3.8742e+08 1e+10
octave:4> power(v1,v2)
ans =
1 4 27 256 3125 46656 8.2354e+05 1.6777e+07 3.8742e+08 1e+10
octave:5> bsxfun(#power, v1, v2)
ans =
1 4 27 256 3125 46656 8.2354e+05 1.6777e+07 3.8742e+08 1e+10

Related

How can I make reverse function of diff of Matlab? [duplicate]

I am trying to resolve why the following Matlab syntax does not work.
I have an array
A = [2 3 4 5 8 9...]
I wish to create an indexed cumulative, for example
s(1) = 2; s(2)=5, s(3)=9; ... and so on
Can someone please explain why the following does not work
x = 1:10
s(x) = sum(A(1:x))
The logic is that if a vector is created for s using x, why would not the sum function behave the same way? The above returns just the first element (2) for all x.
For calculating the cumulative sum, you should be using cumsum:
>> A = [2 3 4 5 8 9]
A =
2 3 4 5 8 9
>> cumsum(A)
ans =
2 5 9 14 22 31
The issue is that 1:x is 1 and that sum reduces linear arrays. To do this properly, you need a 2d array and then sum the rows:
s(x)=sum(triu(repmat(A,[prod(size(A)) 1])'))
You are asking two questions, really. One is - how do I compute the cumulative sum. #SouldEc's answer already shows how the cumsum function does that. Your other question is
Can someone please explain why the following does not work
x = 1:10
s(x) = sum(A(1:x))
It is reasonable - you think that the vector expansion should turn
1:x
into
1:1
1:2
1:3
1:4
etc. But in fact the arguments on either side of the colon operator must be scalars - they cannot be vectors themselves. I'm surprised that you say Matlab isn't throwing an error with your two lines of code - I would have expected that it would (I just tested this on Freemat, and it complained...)
So the more interesting question is - how would you create those vectors (if you didn't know about / want to use cumsum)?
Here, we could use arrayfun. It evaluates a function with an array as input element-by-element; this can be useful for a situation like this. So if we write
x = 1:10;
s = arrayfun(#(n)sum(A(1:n)), x);
This will loop over all values of x, substitute them into the function sum(A(1:n)), and voila - your problem is solved.
But really - the right answer is "use cumsum()"...
Actually what you are doing is
s(1:10)= sum(A(1:[1,2,3...10]))
what you should do is
for i=1:10
s(i)=sum(A(1:i))
end
hope it will help you

How to generate the first twenty powers of x?

So, I've got X, a 300-by-1 vector and I'd like [1, X, X*X, X*X*X, ... , X*X*...*X], a 300-by-twenty matrix.
How should I do this?
X=[2;1]
[X,X.*X,X.*X.*X]
ans =
2 4 8
1 1 1
That works, but I can't face typing out the whole thing. Surely I don't have to write a for loop?
If you want to minimize the number of operations:
cumprod(repmat(X(:),1,20),2) %// replace "20" by the maximum exponent you want
Benchmarking: for X of size 300x1, maximum exponent 20. I measure time with tic, toc, averaging 1000 times. Results (averages):
Using cumprod (this answer): 8.0762e-005 seconds
Using bsxfun (answer by #thewaywewalk): 8.6170e-004 seconds
Use bsxfun for a neat solution, or go for Luis Mendo's extravaganza to save some time ;)
powers = 1:20;
x = 1:20;
result = bsxfun(#power,x(:),powers(:).');
gives:
1 1 1 ...
8 16 32 ...
27 81 243 ...
64 256 1024 ...
... ... ...
The element-wise power operator .^ should do what you need:
x .^ (1:20)
(assuming x is a column vector.)
Use power. It raises something to the power of y, and repeats if y is a vector.
power(x,1:300)
edit: power and .^ operator are equivalent.

Cumulative Sum of a Vector - Syntax

I am trying to resolve why the following Matlab syntax does not work.
I have an array
A = [2 3 4 5 8 9...]
I wish to create an indexed cumulative, for example
s(1) = 2; s(2)=5, s(3)=9; ... and so on
Can someone please explain why the following does not work
x = 1:10
s(x) = sum(A(1:x))
The logic is that if a vector is created for s using x, why would not the sum function behave the same way? The above returns just the first element (2) for all x.
For calculating the cumulative sum, you should be using cumsum:
>> A = [2 3 4 5 8 9]
A =
2 3 4 5 8 9
>> cumsum(A)
ans =
2 5 9 14 22 31
The issue is that 1:x is 1 and that sum reduces linear arrays. To do this properly, you need a 2d array and then sum the rows:
s(x)=sum(triu(repmat(A,[prod(size(A)) 1])'))
You are asking two questions, really. One is - how do I compute the cumulative sum. #SouldEc's answer already shows how the cumsum function does that. Your other question is
Can someone please explain why the following does not work
x = 1:10
s(x) = sum(A(1:x))
It is reasonable - you think that the vector expansion should turn
1:x
into
1:1
1:2
1:3
1:4
etc. But in fact the arguments on either side of the colon operator must be scalars - they cannot be vectors themselves. I'm surprised that you say Matlab isn't throwing an error with your two lines of code - I would have expected that it would (I just tested this on Freemat, and it complained...)
So the more interesting question is - how would you create those vectors (if you didn't know about / want to use cumsum)?
Here, we could use arrayfun. It evaluates a function with an array as input element-by-element; this can be useful for a situation like this. So if we write
x = 1:10;
s = arrayfun(#(n)sum(A(1:n)), x);
This will loop over all values of x, substitute them into the function sum(A(1:n)), and voila - your problem is solved.
But really - the right answer is "use cumsum()"...
Actually what you are doing is
s(1:10)= sum(A(1:[1,2,3...10]))
what you should do is
for i=1:10
s(i)=sum(A(1:i))
end
hope it will help you

vectorized function fminsearch

Thank you very much,first. The first code runs well:
function f=malibu(m1,m2,m3,k,l,t)
f=(m1.*k+(m1+m2).*l).*exp(-m3.*t);
end
function loglik= modelmalibu(p)
global k l t x n m2 m3;
f =malibu(p,m2,m3,k,l,t);
if f==0;
loglik0=0;
else
loglik0=(x.*log(f)+(n-x).*log(1-f));%minus likelihood
end
loglik=sum(-loglik0);
end
clear all;
global n t x k l m2 m3;
m1=0.1;
m2=0.2;
m3=0.3;
t=[1 3 6 9 12 18]';
k=[1 1 2 3 3 4]';
l=[0 0 1 3 4 5]';
y=meltem(m1,m2,m3,k,l,t);
n=100;%trial
x=y.*n;%correct replies
pstart=0.3;
[p1,modelvalue]=fminsearch(#modelmalibu,pstart);
But the similar code for more variable gives error out.
function w=anemon(m1,m2,m3,X,Y,k,l)
w=(m1.*k+(m1+m2).*l)+X.*exp(-m3.*Y);
end
function loglik= modelanemon(p)
global n x m2 m3 X Y k l ;
f =anemon(p,m2,m3,X,Y,k,l);
if f==0;
loglik0=0;
else
loglik0=(x*log(f)+(n-x)*log(1-f));%minus likelihood
end
loglik=sum(-loglik0);
end
clear;
global n x Ydata kdata ldata m1 m2 m3;
%parameters
m1=0.002;
m2=0.0001;
m3=7;
%given data
Xdata=[1 3 6 9 10 12]';
Ydata=[11 13 41 81 121 181]';
kdata=[1 1 2 4 5 4]';
ldata=[1 1 3 3 4 5]';
y=anemon(m1,m2,m3,Xdata,Ydata,kdata,ldata);
n=10;
x=y.*n;
pstart=2;
[pbest,modelvalue]=fminsearch(#modelanemon,pstart);
I've actually tried to use your advises, but if I would write an inequality instead of f==0, the first code fall down as well.
I think you are mixing up two concepts.
vectorization: does refer in how to write your code so it can use some of the acceleration functions in your CPU. it has nothing to do with fminsearch. See: http://en.wikipedia.org/wiki/Vectorization_(parallel_computing)
I suppose you want to write your function such that it accepts a vector as input. Easiest way is to just use a function handle like this:
fh = #(x) my_complicated_function(const1, const2, x(1), x(2), x(3) )
In this case my_complicated_function has 5 inputs, and you take the first 2 constant and input a 3 dim vector for the other 3. Fminsearch will work with that.
You would call
x_opt = fminsearch(fh, [1,2,3])
Besides some tips for the code:
Don't use == for comparison of numbers - go for eg. abs(x1-x2)<0.1 instead
interpanemon looks very strange - it doesn't do what one would call interpolation, and if you look - in every iteration p is recalculated so only the last calculation takes effect. As it looks it should output a constant value - no use optimizing that.
The use of a precalculated Z is probably not what you want. It already determines your optimum. If you use linear optimization the optimum must be already in Z - no need doing interpolation.
The invocation in your case might look like:
min_p = fminsearch(#(x) interpanemon(5,Ydata,x,m2,m3,Z,X,Y,kdata,ldata) ,1)
Overall it looks very unusual - it could really help if you would explain the ideas WHY you choose to do it like this. Also it might help if you restate the problem in a simpler form.

Map function in MATLAB?

I'm a little surprised that MATLAB doesn't have a Map function, so I hacked one together myself since it's something I can't live without. Is there a better version out there? Is there a somewhat-standard functional programming library for MATLAB out there that I'm missing?
function results = map(f,list)
% why doesn't MATLAB have a Map function?
results = zeros(1,length(list));
for k = 1:length(list)
results(1,k) = f(list(k));
end
end
usage would be e.g.
map( #(x)x^2,1:10)
The short answer: the built-in function arrayfun does exactly what your map function does for numeric arrays:
>> y = arrayfun(#(x) x^2, 1:10)
y =
1 4 9 16 25 36 49 64 81 100
There are two other built-in functions that behave similarly: cellfun (which operates on elements of cell arrays) and structfun (which operates on each field of a structure).
However, these functions are often not necessary if you take advantage of vectorization, specifically using element-wise arithmetic operators. For the example you gave, a vectorized solution would be:
>> x = 1:10;
>> y = x.^2
y =
1 4 9 16 25 36 49 64 81 100
Some operations will automatically operate across elements (like adding a scalar value to a vector) while others operators have a special syntax for element-wise operation (denoted by a . before the operator). Many built-in functions in MATLAB are designed to operate on vector and matrix arguments using element-wise operations (often applied to a given dimension, such as sum and mean for example), and thus don't require map functions.
To summarize, here are some different ways to square each element in an array:
x = 1:10; % Sample array
f = #(x) x.^2; % Anonymous function that squares each element of its input
% Option #1:
y = x.^2; % Use the element-wise power operator
% Option #2:
y = f(x); % Pass a vector to f
% Option #3:
y = arrayfun(f, x); % Pass each element to f separately
Of course, for such a simple operation, option #1 is the most sensible (and efficient) choice.
In addition to vector and element-wise operations, there's also cellfun for mapping functions over cell arrays. For example:
cellfun(#upper, {'a', 'b', 'c'}, 'UniformOutput',false)
ans =
'A' 'B' 'C'
If 'UniformOutput' is true (or not provided), it will attempt to concatenate the results according to the dimensions of the cell array, so
cellfun(#upper, {'a', 'b', 'c'})
ans =
ABC
A rather simple solution, using Matlab's vectorization would be:
a = [ 10 20 30 40 50 ]; % the array with the original values
b = [ 10 8 6 4 2 ]; % the mapping array
c = zeros( 1, 10 ); % your target array
Now, typing
c( b ) = a
returns
c = 0 50 0 40 0 30 0 20 0 10
c( b ) is a reference to a vector of size 5 with the elements of c at the indices given by b. Now if you assing values to this reference vector, the original values in c are overwritten, since c( b ) contains references to the values in c and no copies.
It seems that the built-in arrayfun doesn't work if the result needed is an array of function:
eg:
map(#(x)[x x^2 x^3],1:10)
slight mods below make this work better:
function results = map(f,list)
% why doesn't MATLAB have a Map function?
for k = 1:length(list)
if (k==1)
r1=f(list(k));
results = zeros(length(r1),length(list));
results(:,k)=r1;
else
results(:,k) = f(list(k));
end;
end;
end
If matlab does not have a built in map function, it could be because of efficiency considerations. In your implementation you are using a loop to iterate over the elements of the list, which is generally frowned upon in the matlab world. Most built-in matlab functions are "vectorized", i. e. it is more efficient to call a function on an entire array, than to iterate over it yourself and call the function for each element.
In other words, this
a = 1:10;
a.^2
is much faster than this
a = 1:10;
map(#(x)x^2, a)
assuming your definition of map.
You don't need map since a scalar-function that is applied to a list of values is applied to each of the values and hence works similar to map. Just try
l = 1:10
f = #(x) x + 1
f(l)
In your particular case, you could even write
l.^2
Vectorizing the solution as described in the previous answers is the probably the best solution for speed. Vectorizing is also very Matlaby and feels good.
With that said Matlab does now have a Map container class.
See http://www.mathworks.com/help/matlab/map-containers.html