How to clearify matrices in the editor?

2 visualizaciones (últimos 30 días)
Stijn
Stijn el 23 de Nov. de 2015
Comentada: Stijn el 24 de Nov. de 2015
As most of you also do, I use a lot of matrices in MatLab. But, creating these matrices in the editor is a real hassle, especially if you want to have a clear matrix in your code. I'll clarify it with some pictures:
The 'messy' matrix:
The clear matrix:
Does anyone know a way or function that enables me to clear these matrices easily? I spend a lot of time creating 'clear' matrices, so it's easy to identify patterns and/or adjust parameters within the matrix.
The 'Indent' feature in the editor doesn't give the wanted result, since it only spaces the beginning of each row of code.
Thanks in advance!

Respuesta aceptada

Kirby Fears
Kirby Fears el 23 de Nov. de 2015
Here's an example if you're building a matrix with numerical data.
m = [1000,23,0,0; 100,1234,123,0; 0,0,1,1; 0,0,0,1];
mFormatted = [num2str(m), repmat(';',size(m,1),1)];
"mFormatted" is a character array that you can paste into your script.
Since you're using formulas, it would have to be handled as text data. Below is a function that will take a character array input and return a formatted character array that you can paste into your script.
Example of how to call the function:
% Specify m in a single 1xM character array:
m = '[1000,sin(23),0,0; 100,1234,123,0; 0,0,1,1; 0,0,0,1]';
mFormatted = matFormat(m);
Function definition to be saved in matFormat.m:
function outmat = matFormat(inmat)
msplit = strsplit(inmat,';');
msplit2 = cellfun(@(c)strsplit(c,',')',msplit,'UniformOutput',false);
msplit2 = [msplit2{:}]';
for col = 1:size(msplit2,2),
maxWidth = max(cellfun(@(c)length(c),msplit2(:,col)));
if col==size(msplit2,2),
msplit2(:,col) = cellfun(@(c)...
[char(ones(1,maxWidth-length(c))*' ') c ';'],...
msplit2(:,col),'UniformOutput',false);
else
msplit2(:,col) = cellfun(@(c)...
[char(ones(1,maxWidth-length(c))*' ') c ','],...
msplit2(:,col),'UniformOutput',false);
end
end
outmat = cell2mat(msplit2);

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by