How can I reduce the for loop number?

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)

 Accepted Answer

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 Comment

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!

Sign in to comment.

More Answers (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 Comment

Hi! thanks! I actually first time learned about the function "diff". I guess this can potentially be a very powerful function!

Sign in to comment.

Categories

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

Asked:

on 27 Jun 2021

Commented:

on 27 Jun 2021

Community Treasure Hunt

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

Start Hunting!