Is it possible to make GNU Octave to output matrix dimensions together with its content? For example, it should produce smth. like this:
octave:1> X = [1 2; 3 4]
X [2x2] =
1 2
3 4
octave:2> X(1,:)
ans [1x2] =
1 2
In MATLAB, create display.m
in a folder called @double
somewhere in your path with this content:
function display(v)
name = inputname(1);
if isempty(name)
name = 'ans';
end
s = num2cell(size(v));
fprintf('\n%s [%d%s] =\n\n', name, s{1}, sprintf('x%d', s{2:end}));
builtin('disp', v);
end
This way you override the display
method for class double
, and get exactly what you have described. However, this will not work for other classes like int8
, logical
or cell
. You have to override the method for all classes you are interested in. Example:
>> A=ones(2,2,2)
A [2x2x2] =
(:,:,1) =
1 1
1 1
(:,:,2) =
1 1
1 1
While Mohsen's answer does the job indeed, I felt that a separate m-file is somewhat an overkill for this purpose (especially if you don't want to clutter your directory with additional m-files). I suggest using a local anonymous function one-liner instead (let's name it dispf
), so here are its evolution phases :)
The basic anonymous function I came up with is:
dispf = @(x)fprintf('%s =\n\n%s\n', inputname(1), disp(x));
which is essentially equivalent to the output in the command window after entering statements (that do not end with a semicolon, of course). Well, almost... because if inputname
returns an empty string, it doesn't print 'ans'
(and it should). But this can be corrected:
dispf = @(x)fprintf('%s=\n\n%s\n', ...
regexprep([inputname(1), ' '], '^ $', 'ans '), ...
disp(x));
This is basically using regexprep
to match an empty string and replace it with 'ans'
. Finally, we append the dimensions after the variable name:
dispf = @(x)fprintf('%s%s =\n\n%s\n', ...
regexprep([inputname(1), ' '], '^ $', 'ans '), ...
strrep(mat2str(size(x)), ' ', 'x'), ...
disp(x));
Now you can plug this one-liner is into any script without the need for an additional m-file!
Just a proof that it's working:
dispf = @(x)fprintf('%s%s =\n\n%s\n', ...
regexprep([inputname(1), ' '], '^ $', 'ans '), ...
strrep(mat2str(size(x)), ' ', 'x'), ...
disp(x));
A = [1 2; 3 4];
dispf(A)
dispf(A(1, :))
The result is as expected:
A [2x2] =
1 2
3 4
ans [1x2] =
1 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With