Group maths on for loop

1 次查看(过去 30 天)
DARLINGTON ETAJE
DARLINGTON ETAJE 2019-8-8
编辑: Guillaume 2019-8-8
I am trying to solve this
omegas=0:1:10;
RR=40:70;
d=90;
for i=1:length(omegas)
for c=1:length(RR)
gg=d+(omegas.*RR);
end
end
for every value of omegas, I want to calculate gg. The idea is that gg should be a 31 by 11 matrix. Means that each omegas is calculated with all values of RR
  5 个评论
DARLINGTON ETAJE
DARLINGTON ETAJE 2019-8-8
qq=8:10008;
for m = 1:9
for n = 1:10001
A(m, n) = (m+n)+qq;
end
end
this is an easier way of looking at the problem
Guillaume
Guillaume 2019-8-8
this is an easier way of looking at the problem
Not really, it's exactly the same issue. qq is a vector, so you still have a vector that you're trying to store in a scalar.
However, I've understood what you're asking from your description. Sometimes, explaining in words is better than broken code.

请先登录,再进行评论。

回答(2 个)

Adam
Adam 2019-8-8
编辑:Adam 2019-8-8
omegas=0:1:10;
RR=40:70;
d=90;
numOmegas = numel( omegas );
numRR = numel( RR );
gg = zeros( numOmegas, numRR );
for i=1:numOmegas
for c=1:numRR
gg(i,c) =d+(omegas(i).*RR(c));
end
end
You could do it perfectly fine without a loop at all though too probably.

Guillaume
Guillaume 2019-8-8
编辑:Guillaume 2019-8-8
The vectorised version of what you intended with your loop (but didn't achieve):
R=15;
r=5;
epsilon=100;
delta=(R-r)*(epsilon/100);
Theta = 5:10005; %a ROW vector
omega_b1 = (1:9)'; %a COLUMN vector. The two vectors must be along different dimensions
x_b1 = delta*cos(omega_b1) + r*cos(Theta); %automatic expansion of compatible arrays
y_b1 = delta*sin(omega_b1) - r*sin(Theta);
Vb_x1 = -r*Theta.*sin(Theta) - (R - r)*epsilon*omega_b1.*sin(omega_b1)/100;
Vb_y1 = -r*Theta.*cos(Theta) + (R - r)*epsilon*omega_b1.*cos(omega_b1)/100;
ab_x1 = -r*Theta.^2.*cos(Theta) - (R - r)*epsilon*omega_b1.^2.*cos(omega_b1)/100;
ab_y1 = r*Theta.^2.*sin(Theta) - (R - r)*epsilon*omega_b1.^2.*sin(omega_b1)/100;
I've removed a lot of unnecessary brackets.
For how this works, see compatible array sizes

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by