How to clearify matrices in the editor?
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 String 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!