How can I write a script to calculate conditional probability from a user created 2 way table

11 views (last 30 days)
I have a script that gets user input and creates a table. An example looks like this:
Yes No Total
Positive 15 42 57
Negative 32 9 41
Total 47 51 98
I want to then write a script that asks the user if they want to calculate conditional probability, and if they do, to prompt them to put in the row and column names they want to calculate the probability for
For example, P(Yes|Positive)
The user states the row and column names, so I'm finding it difficult to prompt for them in order to calculate the probability.
My script now is:
row = input('Enter number of rows: ');
col = input('Enter number of columns: ');
A = zeros(row + 1,col + 1);
rowNames = input('Enter names of rows separated by a space: ', 's');
rowNames = strsplit(rowNames);
colNames = input('Enter names of column separated by a space: ','s');
colNames = strsplit(colNames);
for i = 1:row
for j = 1:col
str = ['Enter element in row ' num2str(i) ', col ' num2str(j) ': '];
A(i,j) = input(str);
end
end
A;
A(end,1:col) = sum(A(1:row,1:col),1);
A(1:row,end) = sum(A(1:row,1:col),2);
A(end,end) = sum(A(end,1:col));
T = array2table(A,'VariableNames',[colNames {'Total'}],'RowNames',[rowNames, {'Total'}]);

Accepted Answer

KL
KL on 10 Nov 2017
Maybe something like this?
r = input(['Please enter the choice of row for conditional probabilty (between 1 to ' num2str(numel(rowNames)) ' )']);
c = input(['Please enter the choice of column for conditional probabilty (between 1 to ' num2str(numel(colNames)) ' )']);
if(r>=1 && r<=numel(rowNames) && c>=1 && c<=numel(colNames))
%do your thing
%access table like, T{r,c} or T{r,end} T{end,c}
else
disp('Chosen row/column does not exist');
end

More Answers (0)

Categories

Find more on Tables in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!