how can i name each ans in a for loop?
1 view (last 30 days)
Show older comments
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 Comments
Steven Lord
on 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'})
Let's double-check with the simpler approach.
howManyFours = sum(x == 4) % Compare with the table results, between edges 3.5 and 4.5
Instead of referring to a variable named d4 access the 4th element of d, d(4).
howManyFoursApproach2 = d(4)
Accepted Answer
Voss
on 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 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!