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)

 Réponse acceptée

KSSV
KSSV le 27 Juin 2021
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 commentaire

ASHFAQ AHMED
ASHFAQ AHMED le 27 Juin 2021
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!

Connectez-vous pour commenter.

Plus de réponses (1)

DGM
DGM le 27 Juin 2021
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 commentaire

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

Connectez-vous pour commenter.

Catégories

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

Community Treasure Hunt

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

Start Hunting!

Translated by