Shosho
Shosho

Reputation: 69

How can I calculate the relative frequency of a row in a data set using Matlab?

I am new to Matlab and I have a basic question.

I have this data set:

1 2 3 
4 5 7
5 2 7
1 2 3
6 5 3

I am trying to calculate the relative frequencies from the dataset above specifically calculating the relative frequency of x=1, y=2 and z=3

my code is:

    data = load('datasetReduced.txt')
    X = data(:, 1)
    Y = data(:, 2)
    Z = data(:, 3)

    f = 0;
    for i=1:5 
       if X == 1 & Y == 2 & Z == 3 
         s = 1;
       else
         s = 0;
       end
       f = f + s;
    end
    f
    r = f/5

it is giving me a 0 result. How can the code be corrected??

thanks,

Shosho

Upvotes: 2

Views: 458

Answers (2)

Maziyar Gerami
Maziyar Gerami

Reputation: 313

I think you want to count frequency of each instance, So try this

data = [1 2 3 
4 5 7
5 2 7
1 2 3
6 5 3];


[counts,centers] = hist(data , unique(data))

Where centers is your unique instances and counts is count of each of them. The result should be as follow:

counts =

     2     0     0
     0     3     0
     0     0     3
     1     0     0
     1     2     0
     1     0     0
     0     0     2
centers =

     1     2     3     4     5     6     7

That it means you have 7 unique instances, from 1 to 7 and there is two 1s in first column and there is not any 1s in second and third and etc.

Upvotes: 0

Suever
Suever

Reputation: 65460

Your issue is likely that you are comparing floating point numbers using the == operator which is likely to fail due to floating point errors.

A faster way to do this would be to use ismember with the 'rows' option which will result in a logical array that you can then sum to get the total number of rows that matched and divide by the total number of rows.

tf = ismember(data, [1 2 3], 'rows');
relFreq = sum(tf) / numel(tf);

Upvotes: 1

Related Questions