简体   繁体   中英

edit rows in a matrix, MatLab

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?

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;

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  

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM