How can I express these two for loops using only one single for loop?
x_data = [2 6 7 9; 4 9 11 14];
y_data = [8 10 16 31; 15 18 21 24];
for i = 1:length(x_data)
x(i) = [sum((x_data(1,i))-(x_data(2,i)))].^2;
i = i+1;
end
disp(x)
for j = 1:length(y_data)
y(j) = [sum((y_data(1,j))-(y_data(2,j)))].^2;
j = j+1;
end
disp(y)

 채택된 답변

KSSV
KSSV 2021년 6월 27일

0 개 추천

x_data = [2 6 7 9; 4 9 11 14];
y_data = [8 10 16 31; 15 18 21 24];
x = zeros(size(x_data)) ;
y = zeros(size(x_data))
for i = 1:length(x_data)
x(i) = [sum((x_data(1,i))-(x_data(2,i)))].^2;
y(i) = [sum((y_data(1,i))-(y_data(2,i)))].^2;
end
disp(x)
disp(y)

댓글 수: 1

ASHFAQ AHMED
ASHFAQ AHMED 2021년 6월 27일
Hi, thank you for your response. Unfortunately, your code creates some additional rows. However, if I comment out these two lines -
%x = zeros(size(x_data));
%y = zeros(size(x_data));
then it shows the result that my previous code showed!

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

추가 답변 (1개)

DGM
DGM 2021년 6월 27일

1 개 추천

No loops necessary.
x_data = [2 6 7 9; 4 9 11 14];
y_data = [8 10 16 31; 15 18 21 24];
x = diff(x_data,1,1).^2
x = 1×4
4 9 16 25
y = diff(y_data,1,1).^2
y = 1×4
49 64 25 49

댓글 수: 1

ASHFAQ AHMED
ASHFAQ AHMED 2021년 6월 27일
Hi! thanks! I actually first time learned about the function "diff". I guess this can potentially be a very powerful function!

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2021년 6월 27일

댓글:

2021년 6월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by