How to clearify matrices in the editor?
4 views (last 30 days)
Show older comments
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!
0 Comments
Accepted Answer
Kirby Fears
on 23 Nov 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);
More Answers (0)
See Also
Categories
Find more on String in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!