jhon_wick
jhon_wick

Reputation: 247

Matlab, Getting rid of for loop using one liner

Lets assume we have some code. In Matlab editor:

x = zeros(1,10);
x(1,1) = 2;
for k = 1: 9
    x(k+1) = 10 * x(k);
end

Is it possible to write the equation without the for loop?

Upvotes: 0

Views: 160

Answers (3)

Sergey Sigaev
Sergey Sigaev

Reputation: 110

You have an error because it is contrary to the rules of matrix multiplication. My solution below, I used the free analogue of Matlab - Octave, which has a similar syntax:

X=randint(2) % Matrix of size 2 by 2
X =

   1   0
   0   0

Y=2 * 10.^X(:)
Y =

   20
    2
    2
    2

You have a right to multiply the matrix only this type:

M x N on N x P

The result is a matrix of the following dimensions:

M x P


See also:

Element-wise multiplication

Element-wise power


I hope this helped

Upvotes: 0

Amy
Amy

Reputation: 193

Check out the logspace function: x=2*logspace(0,9,10)

Upvotes: 0

Luke Postema
Luke Postema

Reputation: 375

Try this:

x = 2 * 10.^(0:9);

Hope that helps.

Upvotes: 2

Related Questions