Print on screen output result of a nested for loop as a matrix form.
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
hello_world
el 3 de Dic. de 2014
Comentada: hello_world
el 3 de Dic. de 2014
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 comentarios
Stephen23
el 3 de Dic. de 2014
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...
Respuesta aceptada
Star Strider
el 3 de Dic. de 2014
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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!