1
我使用的是Matlab R2014b
(這就是爲什麼我不能使用strings
,但只有char vectors
)。一個class
裏面工作,我不得不從table
變量取數據,格式化之後我的需求,然後將其插入到一個GUI表(的uitable
一個實例,是精確的):Matlab Justify Strings
function UpdateTable(this)
siz = size(mydata);
tab = cell(siz);
tab(:,1) = num2cell(this.Data.ID);
tab(:,2) = cellstr(datestr(this.Data.Date,'dd/mm/yyyy'));
tab(:,3) = arrayfun(@(x){MyClass.TypeDef1{x,1}},this.Data.Type1);
tab(:,4) = arrayfun(@(x){MyClass.TypeDef2{x,1}},this.Data.Type2);
tab(:,5) = arrayfun(@(x){MyClass.FormatNumber(x)},this.Data.Value);
this.UITable.Data = tab;
end
其中:
properties (Access = private, Constant)
TypeDef1 = {
'A1' 'Name A1';
'B1' 'Name B1';
'C1' 'Name C1';
'D1' 'Name D1';
...
}
TypeDef2 = {
'A2' 'Name A2';
'B2' 'Name B2';
'C2' 'Name C2';
'D2' 'Name D2';
...
}
end
methods (Access = private, Static)
function str = FormatNumber(num)
persistent df;
if (isempty(df))
dfs = java.text.DecimalFormatSymbols();
dfs.setDecimalSeparator(',');
dfs.setGroupingSeparator('.');
df = java.text.DecimalFormat();
df.setDecimalFormatSymbols(dfs);
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);
end
str = char(df.format(num));
end
end
一切工作正常。現在我想右鍵將字符串插入到第1列和第5列中,以提高表的可讀性。我找到了適合我需求的Matlab函數,strjust
。閱讀文檔,我看到了它可以用cell arrays of char vectors
使用,所以我修改我的UpdateTable
部分代碼如下:
tab(:,1) = cellstr(num2str(this.Data.ID));
tab(:,5) = strjust(arrayfun(@(x){MyClass.FormatNumber(x)},this.Data.Value));
裏邊反第二個沒有產生變化(字符串仍沒有道理的)。字符串是否應該包含足夠的空白以保持相同的長度?
strjust似乎需要一個單元陣列,這裏的主要問題似乎是你沒有做出一個。如果這是正確的:你能簡單地用for循環創建單元陣列來驗證其餘的工作嗎?之後,您可以隨時將其重寫爲更加優雅。 –
這可能工作? 'tab(:,5)= strjust(arrayfun(@(x){MyClass.FormatNumber(x)},this.Data.Value),'uniformoutput',false));' – Wouter
@Wouter this throws a error「第一個參數不包含字符串的單元數組「。 –