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?

 Accepted Answer

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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Release

R2021b

Asked:

on 20 Mar 2022

Commented:

on 20 Mar 2022

Community Treasure Hunt

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

Start Hunting!