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?

 Réponse acceptée

Voss
Voss le 20 Mar 2022
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

2 commentaires

Joscha Locher
Joscha Locher le 20 Mar 2022
Thank you! :D
Voss
Voss le 20 Mar 2022
You're welcome!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Produits

Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by