Effacer les filtres
Effacer les filtres

How to sum vectors in a loop where it cumulatively sums with the vector created in the previous loop?

3 vues (au cours des 30 derniers jours)
I am currently trying to create a loop where the code sums up numbers from the previous total each time. I have the variable dispSum which adds the displacement vector from row 1 + row 2. Then I want to add dispSum (row1+row2) with the displacment vector from row 3. This would continue until all the displacement vectors have been used so the code is constantly adding the total value. Currently what I have is dispSum adds the previous vector with the next row vector so I am not getting a grand total. How do I change this?
rad1 = [-30.4 -30];
K = 0;
disp = [];
for j = 1:length(medXY1);
K = K+1;
disp(K,1) = medXY2(j,1)-medXY1(j,1);
disp(K,2) = medXY2(j,2)-medXY1(j,2);
end
L0 = dot(disp(1,:),rad1);
k = 1;
dispSum = [];
L = [];
strain = [];
%dispSum1 = plus(disp(1,:),disp(2,:));
for j = 1:length(disp)-1;
dispSum(j,:) = plus(disp(j,:),disp(j+1,:));
L(j,:) = dot(dispSum(j,:),rad1);
strain = (L-L0)/L0;
end

Réponse acceptée

Cris LaPierre
Cris LaPierre le 5 Fév 2019
I think you want to use cumsum. Also, you should take advantage of MATLAB's ability to handle matrices.
rad1 = [-30.4 -30];
disp = medXY2-medXY1;
L0 = dot(disp(1,:),rad1);
dispSum = cumsum(disp);
L = dot(dispSum,ones(length(disp),1)*rad1,2);
strain = (L-L0)/L0;
  5 commentaires
Cris LaPierre
Cris LaPierre le 5 Fév 2019
Each row is the cumulative sum of all the previous rows and itself. If I had the following array:
disp =
2 1
2 3
2 5
2 7
2 9
cumsum would produce an array of the same size where the value in the second row is the sum of the vectors on the 1st and 2nd row. The third row is the sum of the vectors on rows 1-3, etc.
cumsum(disp)
ans =
2 1
4 4
6 9
8 16
10 25
What do you mean it's not giving you the accurate value?
Cris LaPierre
Cris LaPierre le 5 Fév 2019
Ok, so if you want
dispSum(1,:) = disp(1,:)+disp(2,:)
that means dispSum is one row 'shorter' than disp. If that's what you want then do the following
dispSum = cumsum(disp);
dispSum(1,:)=[];

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by