# Caculating the sum of elements and building a vector and a matrix with letters

조회 수: 7(최근 30일)
Lee Cohen 7 Apr 2018
댓글: John BG 8 Apr 2018
I created the following matrix: Here's the code:
n = input('enter n\n');
A=[sym('m%d', [n 1]) sym('x%d', [n 1]) sym('y%d', [n 1]) sym('z%d', [n 1])];
I need to build the following vector and matrix: Once with using loops and once without using loops. I don't succeed to create a sum of elements, that are letters. How Can I build those arrays?

로그인 to comment.

### 채택된 답변

John BG 7 Apr 2018
Hi Lee
1.-
Simulating data
n=12
m=randi([1 10],n,1);
x=randi([-13 13],n,1);
y=randi([-13 13],n,1);
z=randi([-13 13],n,1);
2.-
A=[m x y z]
3.-
the v vector
v=[sum(m.*x) sum(m.*y) sum(m.*z)]
it's the same as
v=[sum(A(:,1).*A(:,2)) sum(A(:,1).*A(:,3)) sum(A(:,1).*A(:,4))]
4.-
Regarding the Inertia matrix I, once you have keyed in the matrix A with the couple lines shown in your question
n = input('enter n\n');
A=[sym('m%d', [n 1]) sym('x%d', [n 1]) sym('y%d', [n 1]) sym('z%d', [n 1])];
the generatrion of I is more compact using vectors m x y and z
To get these vectors one can easily extract m x y z with
m=A(:,1);
x=A(:,2);
y=A(:,3);
z=A(:,3);
then, note that it may be the case that you need I to be 3D so you can address the Inertia moment for any given i-th layer
I0=zeros(3,3,n)
% 1st row of I
I0(1,1,:)=m.*(x).^2
I0(2,1,:)=m.*x.*y
I0(3,1,:)=m.*x.*z
% 2nd row of I
I0(1,2,:)=m.*x.*y
I0(2,2,:)=m.*(y).^2
I0(3,2,:)=m.*z.*y
% 3rd row of I
I0(1,3,:)=m.*x.*z
I0(2,3,:)=m.*y.*z
I0(3,3,:)=m.*(z).^2
5.-
then one can obtain the sum matrix I just adding along 3rd dimension of I0
I=sum(I0,3)
thanks in advance for time and attention
John BG

#### 댓글 수: 6

표시 이전 댓글 수: 3
John BG 8 Apr 2018
no problem, here we go:
1.-
generating data
n=12
m=randi([1 10],n,1);
x=randi([-13 13],n,1);
y=randi([-13 13],n,1);
z=randi([-13 13],n,1);
A=[m x y z] % A, the matrix you start the question with
m=A(:,1);
x=A(:,2);
y=A(:,3);
z=A(:,3);
2.-
the equivalent to
% v=[sum(m.*x) sum(m.*y) sum(m.*z)]
.
is
.
mx=0;
for k=1:1:numel(m)
mx=mx+m(k)*x(k);
end
my=0;
for k=1:1:numel(m)
my=my+m(k)*y(k);
end
mz=0;
for k=1:1:numel(m)
mz=mz+m(k)*z(k);
end
v_sum=[mx my mz]
.
or
.
p=[x y z];
v_sum=[0 0 0]
for k=1:1:numel(m)
v_sum=v_sum+m(k)*p(k,:);
end
3.-
the equivalent to
v=[sum(A(:,1).*A(:,2)) sum(A(:,1).*A(:,3)) sum(A(:,1).*A(:,4))]
is
I_sum=zeros(3);
for k=1:1:numel(m)
I_sum=I_sum+m(k)*[(x(k))^2 x(k)*y(k) x(k)*z(k);x(k)*y(k) (y(k))^2 y(k)*z(k); x(k)*y(k) z(k)*y(k) (z(k))^2];
end
.
or
.
I_sum=zeros(3);
for k=1:1:numel(m)
D=zeros(3);
p1=p(k,:);
for s1=1:1:3
for s2=1:1:3
D(s1,s2)=p1(s1)*p1(s2);
end
end
I_sum=I_sum+m(k)*D;
end
thanks in advance for time and attention
John BG
Lee Cohen 8 Apr 2018
Thank you so much!
John BG 8 Apr 2018
Any time, happy to help :)

로그인 to comment.

### 추가 답변(0개)

이 질문에 답변하려면 로그인을(를) 수행하십시오.