fprintf with cell and double values within a for loop

조회 수: 1 (최근 30일)
Teoman Selcuk
Teoman Selcuk 2021년 12월 3일
댓글: Stephen23 2021년 12월 3일
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
Stephen23
Stephen23 2021년 12월 3일
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

댓글을 달려면 로그인하십시오.

답변 (1개)

Star Strider
Star Strider 2021년 12월 3일
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.
.

카테고리

Help CenterFile Exchange에서 Elementary Math에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by