Effacer les filtres
Effacer les filtres

how can i name each ans in a for loop?

3 vues (au cours des 30 derniers jours)
arian hoseini
arian hoseini le 7 Jan 2022
Commenté : arian hoseini le 8 Jan 2022
Nb=6;
L =[1 2 0.1 0.2 0.02
1 4 0.05 0.2 0.02
1 5 0.08 0.3 0.03
2 3 0.05 0.25 0.03
2 4 0.05 0.1 0.01
2 5 0.1 0.3 0.02
2 6 0.07 0.2 0.025
3 5 0.12 0.26 0.025
3 6 0.02 0.1 0.01
4 5 0.2 0.4 0.04
5 6 0.1 0.3 0.03]
%-------------------------------Program strat her--------------------------
nl = L(:,1); nr = L(:,2); R = L(:,3);
X = L(:,4); Bc = j*L(:,5);
nbr=length(L(:,1)); nbus = max(max(nl), max(nr));
for i=1:Nb
rowsToSum = L(:,1) == i ;
theSum = sum(L(rowsToSum, 4));
disp(theSum)
end
for example
0.7000=a
0.8500=b
0.3600=c
0.4000=d
0.3000=e
0=f
  4 commentaires
Steven Lord
Steven Lord le 7 Jan 2022
Make X a matrix or a cell array depending on whether you want to store how many elements match 1, 2, etc. or you want to store the elements themselves. One easy way to do the former, if all of the bins you want are integer values, is histcounts.
% Sample data
x = randi(10, 1, 100);
% Bin the data
[d, edges] = histcounts(x, 'BinMethod', 'integer');
% Display the results
results = table(d.', edges(1:10).', edges(2:11).', ...
'VariableNames', {'counts', 'left edge', 'right edge'})
results = 10×3 table
counts left edge right edge ______ _________ __________ 12 0.5 1.5 10 1.5 2.5 10 2.5 3.5 8 3.5 4.5 11 4.5 5.5 11 5.5 6.5 14 6.5 7.5 8 7.5 8.5 6 8.5 9.5 10 9.5 10.5
Let's double-check with the simpler approach.
howManyFours = sum(x == 4) % Compare with the table results, between edges 3.5 and 4.5
howManyFours = 8
Instead of referring to a variable named d4 access the 4th element of d, d(4).
howManyFoursApproach2 = d(4)
howManyFoursApproach2 = 8
arian hoseini
arian hoseini le 8 Jan 2022
thanks.

Connectez-vous pour commenter.

Réponse acceptée

Voss
Voss le 7 Jan 2022
You are checking which rows of L have Nb (i.e., 6) in the first column:
rowsToSum = L(:,1) == Nb ;
Instead you should check which rows of L have i in the first column:
rowsToSum = L(:,1) == i ;
And to store them all do this:
theSum = zeros(1,Nb);
for i=1:Nb
rowsToSum = L(:,1) == i ;
theSum(i) = sum(L(rowsToSum, 4));
end
disp(theSum)
  6 commentaires
arian hoseini
arian hoseini le 8 Jan 2022
thank u.your answer was really helpfull but one problem x(1,1) is the sum of all X's whose nl=1 and x(2,2),....
arian hoseini
arian hoseini le 8 Jan 2022
and x(2,1) is 0.2 ....

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by