How can I create a vector of ratios from columns in a matrix?

3 visualizaciones (últimos 30 días)
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 comentarios
KSSV
KSSV el 24 de Ag. de 2018
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.
Gerard Carroll
Gerard Carroll el 24 de Ag. de 2018
Editada: Gerard Carroll el 24 de Ag. de 2018
Sure. Inputting:
StrengthMatrix =[39.0900 39.0900 31.1700;...
25.2700 30.3100 34.0300;...
35.2500 31.1500 36.2500;...
36.7500 39.7600 33.7500;...
33.0100 39.1800 33.2700;...
38.2800 35.1400 33.7500;...
38.4800 39.8200 32.6700;...
34.3800 36.5000 26.2300;...
27.0600 30.0500 35.7900;...
28.2600 34.9300 39.9400;...
27.7300 28.6600 30.3100;...
25.6200 29.4300 39.5600;...
26.6000 35.2000 30.1900;...
34.2400 32.9100 38.2900]
ratiomatrix(StrengthMatrix)
Should give: 0.5714 0.8571 0.9286

Iniciar sesión para comentar.

Respuesta aceptada

Star Strider
Star Strider el 24 de Ag. de 2018
Since ‘a’ is a matrix, you likely have to use two subscripts to it in your if statement, not one.
  4 comentarios
Gerard Carroll
Gerard Carroll el 24 de Ag. de 2018
Editada: Gerard Carroll el 24 de Ag. de 2018
ok that works! So that sums the number of elements in each column that are above 30, then divides by the size of rows in strengthmatrix right?
Star Strider
Star Strider el 24 de Ag. de 2018
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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by