how can i name each ans in a for loop?
조회 수: 2 (최근 30일)
이전 댓글 표시
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
Steven Lord
2022년 1월 7일
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)
채택된 답변
Voss
2022년 1월 7일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!