fprintf with cell and double values within a for loop

1 visualización (últimos 30 días)
Teoman Selcuk
Teoman Selcuk el 3 de Dic. de 2021
Comentada: Stephen23 el 3 de Dic. de 2021
There is a problem with the code down below where it will not display the mean values for (one,two,three) for the corelating string names (iter_names). How would I be able to print the fprintf statements successfully. The code is having trouble with cell and double displaying with the fprintf function.
iter_names = {'One', 'Two', 'Three', 'Four'};
one = {12, 3, 5, 5};
two = {1,2,3,1};
three = {3,3,4,1};
Values = [one,two,three];
Mean_vals = [];
for iter = 1:3
mean_vals = mean(Values(iter));
fprintf('Means for variable %s is %d.2f', iter_names, mean_vals);
Mean_vals(end+1) = mean_vals;
if iter == 3
fprintf('Mean for all values are %d.2f', mean(Mean_vals));
end
end
  1 comentario
Stephen23
Stephen23 el 3 de Dic. de 2021
Rather than storing numeric scalars in cell arrays you should store numeric data in numeric arrays, then your code is simpler and much more efficient:
N = {'One', 'Two', 'Three'};
A = [12,3,5,5;1,2,3,1;3,3,4,1] % even better would be as columns, not rows
A = 3×4
12 3 5 5 1 2 3 1 3 3 4 1
M = mean(A,2);
C = [N;num2cell(M.')];
fprintf('Means for variable %s is %.2f\n',C{:});
Means for variable One is 6.25 Means for variable Two is 1.75 Means for variable Three is 2.75
fprintf('Mean for all values is %.2f\n', mean(M));
Mean for all values is 3.58

Iniciar sesión para comentar.

Respuestas (1)

Star Strider
Star Strider el 3 de Dic. de 2021
The code needed some tweaks.
iter_names = {'One', 'Two', 'Three', 'Four'};
one = {12, 3, 5, 5};
two = {1,2,3,1};
three = {3,3,4,1};
Values = [one;two;three];
Mean_vals = [];
for iter = 1:3
mean_vals = mean([Values{iter,:}]);
fprintf('Means for variable %s is %.2f\n', iter_names{iter}, mean_vals);
Mean_vals(end+1) = mean_vals;
if iter == 3
fprintf('Mean for all values are %.2f\n', mean(Mean_vals));
end
end
Means for variable One is 6.25 Means for variable Two is 1.75 Means for variable Three is 2.75
Mean for all values are 3.58
I will let you explore the changes I made, specifically to ‘Values’ (note the substitution of (;) for (,)) and the functions that use them, as well as to the fprintf calls, all needing cell array indexing.
.

Categorías

Más información sobre Characters and Strings 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!

Translated by