How do I use the matlab.lan​g.makeVali​dName in a proper way to change name on my Excel sheets in a for-loop?

4 ビュー (過去 30 日間)
I want to change name on my sheets so they can be made into a struct array are there any better ways to do this then i do here. Now I focus on just reading a text from a xlsx-format. But I get stuck in the line where I use the matlab.lang.makevalidName function is.
for i=1:n
[~, data_text, data_raw] = xlsread(doc_name, sheets{i}) % Read sheet to Matlab
S = {sheets{i}};
N = matlab.lang.makeValidName(S,'ReplacementStyle','delete')
sheet_struct.(N) = data_raw
end

採用された回答

Guillaume
Guillaume 2016 年 6 月 8 日
As you've done it there is no need to wrap the string sheets{i} into a cell array. The problem you have comes from that and not from makeValidName. Since you pass a cell array, you get a cell array back from makeValidName. You can't use a cell array as a field value, so you would have to extract your modified sheet name from the cell array. So one way to fix it would be:
for i = 1:n
[~, data_text, data_raw] = xlsread(doc_name, sheets{i}) % Read sheet to Matlab
N = matlab.lang.makeValidName(sheets{i}, 'ReplacementStyle', 'delete');
sheet_struct.(N) = data_raw;
end
The other option is to simply call makeValidName outside of the loop at once for all the sheet. That should be faster as well:
N = matlab.lang.makeValidName(sheets, 'ReplacementStyle', 'delete');
for i = 1:n
[~, data_text, data_raw] = xlsread(doc_name, sheets{i}) % Read sheet to Matlab
sheet_struct.(N{i}) = data_raw;
end
Personally, I think that dynamic field names are just as bad an idea as dynamic variables, but that's another topic entirely.
  3 件のコメント
Guillaume
Guillaume 2016 年 6 月 8 日
編集済み: Guillaume 2016 年 6 月 8 日
According to its documentation, matlab.lang.makeValidName was introduced in R2014a.
In 2012b, you can use genvarname instead. It's not as flexible and will generate uglier names but essentially does the same.
Or you could simply use a regular expression. As far as I can tell, your makeValidName usage is equivalent to:
N = regexprep(sheets, '\W', '');
edit: after looking at the code of matlab.lang.makeValidName. Actually, it does a lot more than that, but if you start with a valid excel sheet name, then the above is all that's required to make a valid field name.
studentdavid
studentdavid 2016 年 6 月 8 日
編集済み: studentdavid 2016 年 6 月 8 日
Thanks again! I solved it by using a for loop with strrep and it did the job and generated it quite fast.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by