Reputation: 1
I am trying to print out a very simple table (using fprintf) showing statistics on a set of data I've acquired.
I'm new to Matlab, but - me being used to Java - I think this should work...
Labels = ['Max','Min','Mean','Median','Std. Dev.','Tol. Range'];
for i = 1:6
fprintf('| %c | %4.3f | %4.3f |\n', Labels(i), unmodVals(i), modVals(i));
end
But it doesn't work. :(
For some reason, array indexing for strings doesn't work the same way as it does in Java so i'm completely lost.
it ends up printing out something like:
| M | #### | #### |
| a | #### | #### |
| x | #### | #### |
| M | #### | #### |
| i | #### | #### |
| n | #### | #### |
Can someone point me in the right direction?
Upvotes: 0
Views: 156
Reputation: 9075
You are storing strings in an array called Labels
. In MATLAB, when you write ['a', 'bc']
, it concatenates two strings and produces abc
. Therefore, you should use cell arrays to store strings of different sizes.
Labels = {'Max','Min','Mean','Median','Std. Dev.','Tol. Range'}; %notice the curly braces.
%generating random values of `unmodVals` and `modVals`
unmodVals=randi(1000,[1 6]);
modVals=randi(1000,[1 6]);
for i = 1:6
fprintf('| %s | %4.3f | %4.3f |\n', Labels{i}, unmodVals(i), modVals(i)); %notice change from `%c` to `%s`, c stands for charater, s for string.
end
Note: If you see how your Label
variable looks, you will see this:
Labels = MaxMinMeanMedianStd. Dev.Tol. Range
Upvotes: 0
Reputation: 109119
Character arrays work a little differently in MATLAB. Labels
is not a 1x6 array of strings like you're expecting it to be; the line you have is equivalent to
Labels = strcat('Max','Min','Mean','Median','Std. Dev.','Tol. Range');
So it's a 1x35 array of characters, and you're indexing into it one character at a time. Change Labels
to a cell array of strings as below. You must index into it using braces { }
instead of parentheses ( )
, and change the corresponding fprintf
format specifier to %s
(%c
is for printing characters)
Labels = {'Max','Min','Mean','Median','Std. Dev.','Tol. Range'};
for i = 1:6
fprintf('| %s | %4.3f | %4.3f |\n', Labels{i}, unmodVals(i), modVals(i));
end
Upvotes: 2