How can I create a vector of ratios from columns in a matrix?
3 ビュー (過去 30 日間)
古いコメントを表示
I need to determine the ratio of elements above 30 in each column of a matrix and save in a vector. My current code looks like this:
function output = ratiomatrix(a)
%address all rows, by each column do previous ratio
%but divide by number of elements in column
%probably do it inside for loop and put in vector
[rows,columns] = size(a); %gets number of rows and columns (divide by rows for ratios)
greater = 0; %initialise variable for loop
output = zeros(1,columns); %preallocate variable for greater speeeeeed
for i = 1:columns
for j = 1:rows
if a(j) > 30
greater = greater + 1;
output(i) = greater/rows;
end
end
%output(i) = greater/rows;
%greater = 0;
end
end
The problem i am currently having is that with each iteration, the value of greater includes the previous column and so gives my the wrong ratio. I have tried setting greater back to zero in a number of different places but this does not help. I would appreciate some hints as to how I might fix this, maybe without a complete answer if that's possible?
2 件のコメント
KSSV
2018 年 8 月 24 日
Can you show us an numerical example with output..what you are expecting? You need not struggle with loops to achieve this. Welcome to MATLAB.
採用された回答
Star Strider
2018 年 8 月 24 日
Since ‘a’ is a matrix, you likely have to use two subscripts to it in your if statement, not one.
4 件のコメント
Star Strider
2018 年 8 月 24 日
Correct!
The sum function (and most others in MATLAB) operate by default on the columns (dimension 1), so here it sums each column. You can specify the dimension to operate over as the second argument.
Similarly, since the number of rows are dimension 1,
size(StrengthMatrix,1)
returns that number.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!