Matlab for loop changing each row and column

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

[1 xx^2 x^3 x^4 x^5] [1 yy^2 y^3 y^4 y^5] [1 zz^2 z^3 z^4 z^5] 

etc. The matrix that will have my base values ​​x, y, z, k, etc., is equal to Orig :

 Orig = [ xyzk]; 

and my starting matrix will be

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

My next line of code

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

This for the loop correctly changes the power that each row should raise, however it does not go to the next value in my Orig matrix.

So basically, I need to tell Matlab the path in the for loop to stop using Orig(1,1) and go to Orig(1,2) for line 2.

+4
source share
2 answers

You can do it with a double loop

 Orig = [xyzk]; 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 case as you usually program in Matlab.

Instead, you replicate both Orig and exponent , and perform the calculations in a single, 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 

For several years there was a short version for this, using the bsxfun function. This will automatically execute the extension we made above with repmat , and it will be faster.

 output = bsxfun(@power, Orig', exponent); 
+8
source

to try:

 n = 5; OrigArranged = Orig'*ones(1,n); PowerMat = ones(length(Orig),1) * [1:n]; A = OrigArranged.^PowerMat; 

I will test it when Octave is installed, but it should work.

edit: I fixed minor bugs, now it works

+2
source

Source: https://habr.com/ru/post/1393525/


All Articles