fprintf with cell and double values within a for loop
Afficher commentaires plus anciens
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 commentaire
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
M = mean(A,2);
C = [N;num2cell(M.')];
fprintf('Means for variable %s is %.2f\n',C{:});
fprintf('Mean for all values is %.2f\n', mean(M));
Réponses (1)
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
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.
.
Catégories
En savoir plus sur Matrices and Arrays dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!