Print a matrix in input form

15 vues (au cours des 30 derniers jours)
Bardo
Bardo le 17 Nov 2017
Modifié(e) : Bardo le 20 Nov 2017
Hi,
is there a way to display a matrix in input format?
So a copy/paste would be valid code, like
>> inputForm(A)
A = [1, 2, 3; ...
4, 5, 6; ...
7, 8, 9];
>>
Would be quite helpful for automatic code generation.
Thanks

Réponse acceptée

Bardo
Bardo le 20 Nov 2017
Modifié(e) : Bardo le 20 Nov 2017
function s = inputForm(A, name)
%s = inputForm(A, name)
% Create assignment code from disp output
%
% Inputs
% A: anything disp can handle
% name: variable A is assigned to
% Output
% s: string with expression 'name = A;'
if nargin == 0 % demo
A = randn(4);
name = 'Amat';
end
nl = sprintf('\n');
s = evalc('disp(A)');
if strfind(s, 'Columns')
disp('cannot yet handle that many columns')
disp('you can try to enlarge the Command Window')
error('');
end
s = strrep(s, '[', '');
s = strrep(s, ']', '');
s = strrep(s, nl, ['; ...', nl]);
s = [name, ' = [ ...', nl, s, '];'];

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by