How to Rewrite This Section of Code as a For Loop

조회 수: 2 (최근 30일)
Cody Crouse
Cody Crouse 2024년 3월 14일
댓글: Steven Lord 2024년 3월 15일
Do you know how a for loop equivalent for this would look like? I can't seem visualize what it would look like without having to make significant changes to the loop that I would have created: How can I compute the error without using the sum? I am not sure how to write it in terms of a loop. I am also not sure if I should use a for loop (given that the number of iterations will be the same as for the while loop) or if I should use the while loop:
This is the sevction of Code I want to convert to a for the purposes of a programming assignment that I have for engineering numerical methods:
function E=find_E(X_Prev, X_New);
termA = (X_New - X_Prev)^2;
termA = sum(termA(:))^0.5;
termB = X_New.^2;
termB = sum(termB(:))^0.5;
E = termA/termB;

답변 (2개)

Steven Lord
Steven Lord 2024년 3월 14일
Conceptually, isn't taking the sum of an array of data just the same as repeatedly adding (+) each element to a running total? [The two implementations may not result in exactly, down-to-the-last-bit, identical answers in practice, but in theory shouldn't they match?]
  댓글 수: 3
Cody Crouse
Cody Crouse 2024년 3월 15일
In addition, I am looking to rewrite this text of code as a loop:
function E = find_E(X_Prev, X_New)
termA = (X_New - X_Prev).^2;
termA = sum(termA(:))^0.5;
termB = X_New.^2;
termB = sum(termB(:))^0.5;
E = termA/te
Steven Lord
Steven Lord 2024년 3월 15일
Hint: take a look at the numel function.

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


Walter Roberson
Walter Roberson 2024년 3월 15일
termAsum = 0;
for term = termA(:).'
termAsum = termAsum + term;
end
  댓글 수: 2
Cody Crouse
Cody Crouse 2024년 3월 15일
Does this serve as a resplacement for my code section? I am asking because I already that E = find_E(X_Prev, X_New) several times in my code. In addition, my term statements are underneath it.
Walter Roberson
Walter Roberson 2024년 3월 15일
That replaces
termA = sum(termA(:));
Note: it leaves out the ^0.5

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

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by