for loop
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
更多回答(3 个)
Andrei Bobrov
2012-4-1
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
2012-4-1
Change "bi,j,k" to "b(i,j,k)"
2 个评论
Image Analyst
2012-4-2
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!