how can i name each ans in a for loop?

1 回表示 (過去 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 Center および File ExchangeLoops 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