Matrix calculation without Loop

for j = (i+1 : n)
A(j,i) = (1/A(i,i))*(A(j,i) - sum(A(j,1 : i-1) .* A(i, 1 : i-1)));
end
I am pretty new to matlab and got tasked to get rid of for loops as an excercise. This is the last one left (that apperantly isn't necessary) but I cannot get rid of it for the life of me... Mostly due to the index j inside the sum. Ideally Id get the sum as a vector where the j-th element is defined as sum(A(j,1 : i-1) .* A(i, 1 : i-1))) but that would again require a loop
Can anyone help?

 采纳的回答

Try this instead of that loop:
A(i+1:n,i) = (1/A(i,i))*(A(i+1:n,i)-sum(A(i+1:n,1:i-1).*A(i,1:i-1),2));
To test it:
% using that line in a loop over i:
n = 5;
A = magic(n);
for i = 1:n
A(i+1:n,i) = (1/A(i,i))*(A(i+1:n,i)-sum(A(i+1:n,1:i-1).*A(i,1:i-1),2));
end
% the original j loop (within an i loop):
n = 5;
A_original = magic(n);
for i = 1:n
for j = i+1:n
A_original(j,i) = (1/A_original(i,i))*(A_original(j,i) - sum(A_original(j,1:i-1).*A_original(i,1:i-1)));
end
end
% check that they are the same:
isequal(A,A_original)
ans = logical
1

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

版本

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by