for loop
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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
0 Commenti
Risposta accettata
Più risposte (3)
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)
Image Analyst
il 1 Apr 2012
Change "bi,j,k" to "b(i,j,k)"
2 Commenti
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.
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!