Azzera filtri
Azzera filtri

for loop

1 visualizzazione (ultimi 30 giorni)
rami
rami il 1 Apr 2012
Hi
I have matrix M(3,3)
I need to solve this equation
for i=1:3
for j=1:3
for k=1:3
bi,j,k=(1/2)*(diff(M(k,j),theta1)+diff(M(k,i),theta1)-diff(M(i,j),theta1))
end
end
end
I need to have the answers in form
b111
b112
b121
....
b333
how i can do that thx

Risposta accettata

Walter Roberson
Walter Roberson il 1 Apr 2012

Più risposte (3)

Andrei Bobrov
Andrei Bobrov il 1 Apr 2012
eg
syms x
M = [x^4,2,x^(4/5)-4*x;x,2*x^3,log(x);exp(3*x),x,3*x];
solution
dM = diff(M,x);
idx = fliplr(fullfact(size(M,1)*ones(3,1)));
id = cellfun(@(x)sub2ind(size(M),idx(:,x(1)),idx(:,x(2))),{[3 2],[3 1],[1 2]},'un',0);
b = 1/2*(dM(id{1}) + dM(id{2}) - dM(id{3}));
ADD on Rami comment
eg
syms x y z
M = [x^4*z-y,z*2,x*z^(4/5)-4*x*y;x,2*z*y*x^3,log(x)/y;z*exp(3*x)-y,z*x*y^2,z*(y-z^3)*3*x];
theta = [x y z];
solution
dM = arrayfun(@(ii)diff(M,theta(ii)),1:numel(theta),'un',0);
dM = cat(3,dM{:});
[k j1 i1] = ndgrid(1:numel(theta));
id = {i1(:) j1(:) k(:)};
s = [3 2 1;3 1 2;1 2 3];
idx = cell2mat(arrayfun(@(x)sub2ind(size(dM),id{s(x,:)}),1:3,'un',0));
b = dM(idx)*[1;1;-1]/2
OR variant with loop for..end
for i1=1:3
for j1=1:3
for k=1:3
b1(i1,j1,k) = (1/2)*(diff(M(k,j1),theta(i1))...
+diff(M(k,i1),theta(j1))-diff(M(i1,j1),theta(k)));
end
end
end
b_ijk = reshape(permute(b1,[3 2 1]),[],1)
  1 Commento
rami
rami il 1 Apr 2012
Thx for your answer:
In the solution I can not know
b111
b112
b121
b122
...etc
and in my example I want to make some modify that there are 3 variables theta1, theta2, theta3
for i=1:3
for j=1:3
for k=1:3
bijk=(1/2)*(diff(M(k,j),theta(i))+diff(M(k,i),theta(j))-diff(M(i,j),theta(k)))
end
end
end
So i want to find the values
b111
b112
........

Accedi per commentare.


Image Analyst
Image Analyst il 1 Apr 2012
Change "bi,j,k" to "b(i,j,k)"
  2 Commenti
rami
rami il 1 Apr 2012
Thx
I try but wasn't useful
Image Analyst
Image Analyst il 2 Apr 2012
Well like Andrei and I both suggested, you should use a 3D matrix and not individually named variables. In fact the answer you accepted, Walter's, also recommends using an indexed matrix and recommends against using what you say you wanted. So we're left confused. But whatever.....as long as you got something you like, even though it's not recommended.

Accedi per commentare.


rami
rami il 1 Apr 2012
thx The link was so useful and the answer will be for one variable
for i=1:3 for j=1:3 for k=1:3
eval(sprintf('b%d%d%d= (1/2)*(diff(M(k,j),theta1)+diff(M(k,i),theta1)-diff(M(i,j),theta1))', i,j,k));
end
end
end

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by