fprintf with cell and double values within a for loop
조회 수: 1 (최근 30일)
이전 댓글 표시
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
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
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));
답변 (1개)
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
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.
.
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!