[英]Matlab multiply each row in matrix by different number
Say that I have a matrix: 假设我有一个矩阵:
A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ; 10 11 12];
Is there a way to multiply : 有没有办法繁殖:
row 1 by 1 第1行第1行
row 2 by 2 第2排2
row 3 by 3 第3行第3行
and so on? 等等?
I am able to do this with for loops, however it if for an assignment where they want us to use matrices. 我能够使用for循环执行此操作,但是如果对于他们希望我们使用矩阵的分配,它。 In the actual assignment
A
is filled with random number but each row which by multiplied consecutively. 在实际分配中,
A
用随机数填充,但每行连续相乘。
Thanks, any help is much appreciated 谢谢,非常感谢任何帮助
You just need to multiply a diagonal matrix by A like so. 你只需将对角矩阵乘以A就好了。
A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ; 10 11 12];
disp(diag([1 2 3 4]) * A);
1 2 3
8 10 12
21 24 27
40 44 48
You can use bsxfun
to accomplish this easily and very quickly 您可以使用
bsxfun
轻松快速地完成此任务
out = bsxfun(@times, [1 2 3 4].', A)
In newer versions of MATLAB (R2016b and newer) you can actually replace bsxfun
with simply *
在较新版本的MATLAB(R2016b和更新版本)中,您实际上可以简单地用
*
替换bsxfun
out = [1 2 3 4].' * A;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.