如果您没有 R2013b 或更高版本,最好的解决方案是围绕普通矩阵编写一个小类,它只实现构造函数和disp
函数。
这是一个示例:
>> W = WeeklyStatistics(rand(7,5), 'Mean', 'Median', 'Minimum', 'Maximum', 'Variance')
W =
Mean Median Minimum Maximum Variance
Monday 0.228977 0.442678 0.084436 0.263803 0.853031
Tuesday 0.913337 0.106653 0.399783 0.145539 0.622055
Wednesday 0.152378 0.961898 0.259870 0.136069 0.350952
Thursday 0.825817 0.004634 0.800068 0.869292 0.513250
Friday 0.538342 0.774910 0.431414 0.579705 0.401808
Saturday 0.996135 0.817303 0.910648 0.549860 0.075967
Sunday 0.078176 0.868695 0.181847 0.144955 0.239916
>>
这是我为此使用的课程:
classdef WeeklyStatistics < double
properties
columnTitles
weekDays = {
'Monday'
'Tuesday'
'Wednesday'
'Thursday'
'Friday'
'Saturday'
'Sunday'
};
end
methods
function obj = WeeklyStatistics(M, varargin)
obj = obj@double(M);
%// Just copy the data
obj.columnTitles = varargin;
%// NOTE: very basic checks (you might want to think a bit more
%// about these
if ~all(cellfun('isclass', obj.columnTitles, 'char'))
error('WeeklyStatistics:invalid_column_titles',...
'Invalid column title format. All column titles should be given as strings.');
end
if size(obj,2) ~= numel(obj.columnTitles)
error('WeeklyStatistics:dimension_mismatch',...
'Number of columns in data disagrees with number of column titles.');
end
if size(obj,1) > numel(obj.weekDays)
error('WeeklyStatistics:dimension_mismatch',...
'Number of rows in data exceeds number of days in a week.');
end
end
%// These are needed to make the matrix behave like an ordinary matrix
function R = subsref(obj,varargin)
R = subsref(double(obj), varargin{:}); end
function R = subsasgn(obj,varargin)
R = WeeklyStatistics(subsasgn(double(obj), varargin{:}), obj.columnTitles{:}); end
%// Show the matrix
function disp(obj)
%// Print column titles
fprintf(1,repmat(' ',1,16));
fprintf(1,'%16s', obj.columnTitles{:});
fprintf(1,'\n');
%// Print data for all weekdays
dobj = double(obj);
for ii = 1:size(dobj,1)
fprintf(1, '%16s', obj.weekDays{ii});
fprintf(1,'%16f',dobj(ii,:));
fprintf(1,'\n');
end
fprintf(1,'\n');
%// NOTE: proper disp() implementations check the current setting
%// of format() and adjust spacing and formatting accordingly
end
end
end