How to clearify matrices in the editor?

조회 수: 2 (최근 30일)
Stijn
Stijn 2015년 11월 23일
댓글: Stijn 2015년 11월 24일
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!

채택된 답변

Kirby Fears
Kirby Fears 2015년 11월 23일
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);
  댓글 수: 1
Stijn
Stijn 2015년 11월 24일
Thanks, that's indeed what I meant!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by