fprintf with cell and double values within a for loop

1 view (last 30 days)
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 Comment
Stephen23
Stephen23 on 3 Dec 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

Sign in to comment.

Answers (1)

Star Strider
Star Strider on 3 Dec 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.
.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!