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!