필터 지우기
필터 지우기

for loop

조회 수: 1 (최근 30일)
rami
rami 2012년 4월 1일
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

채택된 답변

Walter Roberson
Walter Roberson 2012년 4월 1일

추가 답변 (3개)

Andrei Bobrov
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)
  댓글 수: 1
rami
rami 2012년 4월 1일
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
........

댓글을 달려면 로그인하십시오.


Image Analyst
Image Analyst 2012년 4월 1일
Change "bi,j,k" to "b(i,j,k)"
  댓글 수: 2
rami
rami 2012년 4월 1일
Thx
I try but wasn't useful
Image Analyst
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.

댓글을 달려면 로그인하십시오.


rami
rami 2012년 4월 1일
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

카테고리

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