Reputation: 17
I have a matrix A
and I want to multiply every row by 2 using a for
loop.
A = [1 2 3;
4 5 6;
7 8 9];
So essentially matlab should output:
[2 4 6;
8 10 12;
14 16 18];
I tried:
A = [1 2 3 ; 4 5 6 ; 7 8 9];
for i=1:3
x= A([i],:)*2;
end
but x
outputs as [14 16 18]
.
How can I get my desired output?
Upvotes: 0
Views: 2499
Reputation: 203
For loops are very very inefficient in MAtlab. I would suggest you learn to work around it when using matlab. For something small like this you may not see any detrimental effect, but for anything large scale, it's a no.
Anyway, for your problem, you can just do x = A*2
. That should give you your solution.
Upvotes: -1
Reputation: 1
In think your answers are getting overwritten every time you go in the for loop. You may be able to do something like this:
for i=1:3
x([i],:) = A([i],:)*2;
end
Upvotes: 0
Reputation: 26069
With a for loop that will be:
for n=1:size(A,1)
x(n,:)=2*A(n,:);
end
But it is much easier to get the same result without a for loop:
x=2*A;
Upvotes: 2