First, let's declare the symbolics easier using sym
:
T = sym('T%d%d', [4 4]);
A = sym('A%d%d', [4 4]);
L = sym('L', [4 1]);
There are several problems with the original code; 1. f
is being replaced in each inner iteration. 2. The inner result should be scalar and thus I
must not appear there. (Note that you can also define I
like eye(4)
instead of writing it manually.)
Here is the corrected version:
f = cell(4,1); % Initialize equation system
for r = 1:k
for k = 1:4
for i = 1:4
f{r}(i,k) = T(i,k) * A(r,k);
end
end
f{r} = f{r} - L(r)*diag(A(r,:));
end
f{i}
would be the ith
slice.
Note: As @Schorsch pointed out (and Matlab also shows a warning) always try to use another variable name other than i
(or j
), since they represent the imaginary unit.
Just for fun you can use repmat
to remove the two inner loops:
for r = 1:4
f{r} = T .* repmat(A(r,:), [4 1]) - L(r)*diag(A(r,:));
end
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…