Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab for loop changing each row & column

I am trying to create a matrix to look like this:

[1 x x^2 x^3 x^4 x^5]
[1 y y^2 y^3 y^4 y^5]
[1 z z^2 z^3 z^4 z^5]

and so on. The matrix which is going to have my base vales of x,y,z,k etc is Orig:

Orig = [ x y z k];

and my starting matrix is going to be

A = [1 x x^2 x^3 x^4 x^5];

My next line of code is

for i=(2:10)
    A(i)=A(i)^A(:,i)
end

This for loop correctly changes the power that each row needs to be raised too, however it will not go to the next value in my Orig matrix.

So basically, I need to tell Matlab a way, within the for loop, to stop using Orig(1,1) and go to Orig(1,2) for row 2.

like image 230
Michael Avatar asked Dec 27 '22 07:12

Michael


1 Answers

You can do this with a double loop

Orig = [x y z k];
exponent = [0 1 2 3 4 5];

%# preassign output to speed up loop
output = zeros(length(Orig),length(exponent));

%# loop over all elements in Orig
for r = 1:length(Orig)
%# loop over all exponents
for c = 1:length(exponent)
output(r,c) = Orig(r)^exponent(c);
end
end

However, this is not the way you'd normally program this in Matlab.

Instead, you'd replicate both Orig and exponent, and do the calculation in one, vectorized operation:

%# transpose orig so that it is a n-by-1 array
repOrig = repmat(Orig',1,length(exponent); %'#
repExp  = repmat(exponent,length(Orig),1);
%# perform the exponent operation in one go
output = repOrig .^ repExp; %# note the ".", it applies operations element-wise

Since a few years, there has been a shortcut version for this, using the function bsxfun. This will automatically perform the expansion we did above with repmat, and it will be faster.

output = bsxfun(@power, Orig', exponent);
like image 184
Jonas Avatar answered Jan 04 '23 18:01

Jonas