how can i name each ans in a for loop?

조회 수: 2 (최근 30일)
arian hoseini
arian hoseini 2022년 1월 7일
댓글: arian hoseini 2022년 1월 8일
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
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'})
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 2022년 1월 8일
thanks.

댓글을 달려면 로그인하십시오.

채택된 답변

Voss
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
arian hoseini
arian hoseini 2022년 1월 8일
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 2022년 1월 8일
and x(2,1) is 0.2 ....

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by