Print on screen output result of a nested for loop as a matrix form.

3 ビュー (過去 30 日間)
hello_world
hello_world 2014 年 12 月 3 日
コメント済み: hello_world 2014 年 12 月 3 日
I have the following code:
A = [1 1 3 2; 2 3 0 2; 3 1 0 2];
B = [1 3 5; 0 1 9; 10 2 0; 0 1 1];
[r, c] = size(A);
y = zeros(r,c);
p = zeros(r,c);
for i = 1:c %Looping through the column.
for j = 1:r %Looping through the row in that that column.
y(j,i) = sum(A(:,[i]) == A(j,i)); %Compare each column of the matrix with the entries in that column.
p(j,i) = y(j,i)/r; %Probability of each entry of a column within that column.
end
end
It gives the output as follows:
For the 1st column: p(1) = p(2) = p(3) = 1/3
For the 2nd column: p(1) = 2/3, p(3) = 1/3
For the 3rd column: p(3) = 1/3, p(0) = 2/3
For the 4th column: p(2) = 3/3 = 1.
Though, I want to print it in a matrix form, i.e., as follows:
1/3 2/3 1/3 1
P(A) = 1/3 1/3 2/3 1 ; P(B) = similarly! ; P(C) = ...
1/3 2/3 2/3 1
that means, I want to print out an out in a matrix form for above code. However, my code shows the output matrix (as a variable) only for the final matrix (say, for C), and nothing for A and B in workspace. I will like to have matrices (variables) in workspace for A, B and C.
Please advise!
  2 件のコメント
Stephen23
Stephen23 2014 年 12 月 3 日
First piece of advice: do not use i or j as the loop variables, as these are both names of the inbuilt imaginary unit . Shadowing inbuilt functions and values like that causes problems that you really don't want to deal with...
hello_world
hello_world 2014 年 12 月 3 日
Thank you. I did not know that. I will remove them.

サインインしてコメントする。

採用された回答

Star Strider
Star Strider 2014 年 12 月 3 日
Use rats to get the fractions:
P = rats(p);
L = size(p,2);
for k1 = 1:r
if k1 ~= 2
fprintf(1, '\n\t\t[%s]', P(k1,:)')
else
fprintf(1, '\n P(A) = [%s]', P(k1,:)')
end
end
fprintf(1,'\n')
produces:
[ 1/3 2/3 1/3 1 ]
P(A) = [ 1/3 1/3 2/3 1 ]
[ 1/3 2/3 2/3 1 ]

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by