How to generate the first twenty powers of x? - matlab

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.

Related

How to store all columns of the matrix in Matlab workspace

Sorry for the vague title, but I wasn't sure how to name it properly.
Let's say I have this vector:
v=[2 5 8]';
Also I have the range of numbers as follow:
x=2:4
I want to create a for loop that will multiply the vector by 2, then use this newly created vector and multiply it by 3 and then use that and multiply it by 4. What I essentialy want is a 3 by 3 matrix
When I code something like this:
v=[2 5 8]';
for i= 2:4
k=v*i
end
This doesn't work because
a) Instead of multiplying by the next number in the loop it just adds the elements to itself i.e( in the second iteration I want (12, 30, 48)' and not (6,15,24)'
b) It doesn't store all 3 sets of values in the workspace.
EDIT
for i=1:1:length(x)
c1=fftshift(fft(u0z));
c2=exp(-1j*(p^2*x(i)/(2*lamda))).*c1;
c3=ifft(ifftshift(c2));
u1=exp(1j*lamda*(n(i)^2-1)*x(i)/2).*c3;
u0z=u1
end
Edit 2
for k=1:1:length(x)
c1=fftshift(fft(u0z));
c2=exp(-1j*(p^2*x(k)/(2*lamda))).*c1;
c3=ifft(ifftshift(c2));
u1=exp(1j*lamda*(n(k)^2-1)*x(i)/2).*c3;
u0z=u1;
mat(:,k)=u0z;
end
Using MATLAB's cumprod and implicit expansion (for MATLAB before R2016b, you need bsxfun for that), that's a one-liner:
v * cumprod(x)
% bsxfun(#times, v, cumprod(x))
ans =
4 12 48
10 30 120
16 48 192
Hope that helps!

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

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

How to reshape vector into sqare matrix?

I have a vector of certain size and I want to reshape it into a square matrix. Here is an example: Let's say the vector is of size 784. Then I would create a matrix of size 28x28. In Matlab I would do it with the following command:
reshape(x,28,28)
Of course it can be possible that it is not possible to have an exact square matrix. In this case the matrix should as squarish as possible.
How can I do this calculation? That means how can I calculate the values a and b in reshape(x,a,b)?
Start with a equal to the square root of numel(x) rounded down. If that number doesn't divide numel(x), subtract 1 and try again. That way you end with a equal to the closest integer to sqrt(x) (from below) that divides numel(x). b would then be numel(x)/a, but you can simply use [] as the third argument to reshape:
a = floor(sqrt(numel(x)));
while mod(x,a)
a = a-1;
end
result = reshape(x,a,[]);
Example:
x = 1:20;
gives
result =
1 5 9 13 17
2 6 10 14 18
3 7 11 15 19
4 8 12 16 20
One possible approach:
x = rand(1, 784);
divisors = find(rem(numel(x), 1:numel(x)) == 0);
[~, idx] = min(abs(divisors - sqrt(numel(x))));
x = reshape(x, divisors(idx), numel(x) / divisors(idx));
Let me explain:
Suppose you have a vector named x:
x = rand(1, 784);
First, you find the divisors of the size of x:
divisors = find(rem(numel(x), 1:numel(x)) == 0);
Then, you proceed to choose the divisor which is closest to the square root of x's size:
[~, idx] = min(abs(divisors - sqrt(numel(x))));
Finally, you reshape x using that divisor (and the corresponding multiple):
x = reshape(x, divisors(idx), numel(x) / divisors(idx));
It is not a simple problem to find closest factors of an integer. You need to use the MATLAB answers to the question Input an integer, find the two closest integers which, when multiplied, equal the input. From that question if you use the answer that provides the function findIntegerFactorsCloseToSquarRoot, you can use the following code to reshape.
[a, b] = findIntegerFactorsCloseToSquarRoot(numel(x));
reshape(x, a, b);
I suggest you to first check whether the number is prime or not by isprime(784).
Then you can use prime_factors = factor(784) to get the integer factorization of the number. (Depending on the MATLAB version you may use ifactor(784))
The rest needs just a little more work on prime_factors.

Find extremum of multidimensional matrix in matlab

I am trying to find the Extremum of a 3-dim matrix along the 2nd dimension.
I started with
[~,index] = max(abs(mat),[],2), but I don't know how to advance from here. How is the index vector to be used together with the original matrix. Or is there a completely different solution to this problem?
To illustrate the task assume the following matrix:
mat(:,:,1) =
23 8 -4
-1 -26 46
mat(:,:,2) =
5 -27 12
2 -1 18
mat(:,:,3) =
-10 49 39
-13 -46 41
mat(:,:,4) =
30 -24 18
-40 -16 -36
The expected result would then be
ext(:,:,1) =
23
-46
ext(:,:,2) =
-27
18
ext(:,:,3) =
49
-46
ext(:,:,4) =
30
-40
I don't know how to use the index vector with mat to get the desired result ext.
1) If you want to find a maximum just along, let's say, 2d dimension, your variable index will be a matrix having dimensions (N,1,M), where N and M are number of elements of your matrix in the first and third dimensions respectively. In order to remove dummy dimensions, there is function squeeze() exist: index=squeeze(index) After that size(index) gives N,M
2) Depending on your problem, you probably need matlab function ind2sub(). First, you take a slice of your matrix, than find its maximum with linear indexing, and than you can restore your indicies with int2sub(). Here is an example for a 2D matrix:
M = randn(5,5);
[C,I] = max(M(:));
[index1,index2] = ind2sub(size(M),I);
Same method allows to find the absolute maximal element in whole 3D matrix.
Use ndgrid to generate the values along dimensions 1 and 3, and then sub2ind to combine the three indices into a linear index:
[~, jj] = max(abs(mat),[],2); %// jj: returned by max
[ii, ~, kk] = ndgrid(1:size(mat,1),1,1:size(mat,3)); %// ii, kk: all combinations
result = mat(sub2ind(size(mat), ii, jj, kk));
A fancier, one-line alternative:
result = max(complex(mat),[],2);
This works because, acccording to max documentation,
For complex input A, max returns the complex number with the largest complex modulus (magnitude), computed with max(abs(A)).

Stability (Numerical analysis)

I'm trying to find the max machine number x that satisfies the following equation: x+a=a, where a is a given integer. (I'm not allowed to use eps.)
Here's my code (which is not really working):
function [] = Largest_x()
a=2184;
x=0.0000000001
while (x+a)~=a
x=2*x;
end
fprintf('The biggest value of x in order that x+a=a \n (where a is equal to %g) is : %g \n',a,x);
end
Any help would be much appreciated.
The answer is eps(a)/2.
eps is the difference to the next floating point number, so if you add half or less than that to a float, it won't change. For example:
100+eps(100)/2==100
ans =
1
%# divide by less than two
100+eps(100)/1.9==100
ans =
0
%# what is that number x?
eps(100)/2
ans =
7.1054e-15
If you don't want to rely on eps, you can calculate the number as
2^(-53+floor(log2(a)))
You're small algorithm is certainly not correct. The only conditions where A = X + A are when X is equal to 0. By default matlab data types are doubles with 64 bits.
Lets pretend that matlab were instead using 8 bit integers. The only way to satisfy the equation A = X + A is for X to have the binary representation of [0 0 0 0 0 0 0 0]. So any number between 1 and 0 would work as decimal points are truncated from integers. So again if you were using integers A = A + X would resolve to true if you were to set the value of X to any value between [0,1). However this value is meaningless because X would not take on this value but rather it would take on the value of 0.
It sounds like you are trying to find the resolution of matlab data types. See this: http://www.mathworks.com/help/matlab/matlab_prog/floating-point-numbers.html
The correct answer is that, provided by Jonas: 0.5 * eps(a)
Here is an alternative for the empirical and approximate solution:
>> a = 2184;
>> e = 2 .^ (-100 : 100); % logarithmic scale
>> idx = find(a + e == a, 1, 'last')
idx =
59
>> e(idx)
ans =
2.2737e-013