Understand a command line to create a matrix

4 次查看(过去 30 天)
Hi all,
I am trying to write the following matlab line into another program, I already found it in the internet, it works perfectly, but I can not understand excatly how it work ??
clc; nelments= 3; npoint= 5;
connect=(1:npoint) + (npoint-1)*(0:nelments-1).'

采纳的回答

Geoff Hayes
Geoff Hayes 2021-10-8
@Mark Sc - this is an interesting piece of code. Given that
>> x = (1:npoint)
x =
1 2 3 4 5
and that
>> y = (npoint-1)*(0:nelments-1).'
y =
0
4
8
we are trying to add a 1x5 matrix with a 3x1 matrix with the output being a 3x5. Looking at the plus for 2-D inputs, if one input is a column vector, and the other is a row vector then your output (in this case) will be that 3x5 matrix where we add 0 to each element of x to get the first row of the new matrix, 4 to each element of x to get the second row of the new matrix, and 8 to each element of x to get the third row.
>> x + y
ans =
1 2 3 4 5
5 6 7 8 9
9 10 11 12 13
  2 个评论
Mark Sc
Mark Sc 2021-10-8
Thank you for clear explanation,
Not sure if possible to ask could we do the same in python ??
If so, could you provide it ??
Geoff Hayes
Geoff Hayes 2021-10-8
@Mark Sc - I tried doing something similar in Python but observed an error
Traceback (most recent call last):
File "py-add.py", line 4, in <module>
c=a+b
ValueError: operands could not be broadcast together with shapes (5) (3)
so from this one example it seems that it behaves a little differently than MATLAB. It shouldn't be too hard to write the code to do what you want though.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by