How to replace elements of a cell array using a containers.Map

11 ビュー (過去 30 日間)
Bill Tubbs
Bill Tubbs 2021 年 1 月 19 日
コメント済み: Bill Tubbs 2021 年 2 月 1 日
I have a cell array of VariableNames that Matlab created when reading a csv file. I want to change them to my own choice of names however, the order of the names is not guaranteed.
iddata = readtable('data.csv');
var_names = iddata.Properties.VariableNames;
names_to_replace = {'TonnageDeBSA', 'D__bitD___eauAuBSA', ...
'PressionPalierSAG', 'PuissanceSAG'};
replacements = {'TonnageBSA', 'DebitEauBSA', ...
'PressionPalierSAG', 'PuissanceSAG'};
replace_map = containers.Map(names_to_replace, replacements);
Obviously I could use a for loop:
new_var_names = {};
for i=1:numel(var_names)
new_var_names(i) = {replace_map(var_names{i})};
end
But I am hoping there is an easier way.
Does MATLAB have anything like a list comprehension in Python?
new_var_names = {replace_map[name] for name in var_names}
Even better if there is a way to handle failed matches:
new_var_names = {replace_map[name] for name in var_names if name in replace_map}

採用された回答

Puru Kathuria
Puru Kathuria 2021 年 1 月 31 日
You might want to try out arrayfun, which can help you in applying a function to each element of array.
Otherwise, you can also do the above mentioned operation traditionally using for loop.
  2 件のコメント
Bill Tubbs
Bill Tubbs 2021 年 1 月 31 日
I couldn't get arrayfun to work but cellfun does.
Is this what you meant?
new_var_names = cellfun(@(s) replace_map(s), var_names, 'UniformOutput', false)
per isakson
per isakson 2021 年 2 月 1 日
編集済み: per isakson 2021 年 2 月 1 日
Most likely, yes. Had the texts been stored in string arrays then arrayfun had done the job.

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

その他の回答 (1 件)

per isakson
per isakson 2021 年 2 月 1 日
With string and arrayfun on R2018b
%%
names_to_replace = ["TonnageDeBSA", "D__bitD___eauAuBSA", ...
"PressionPalierSAG", "PuissanceSAG"];
replacements = ["TonnageBSA", "DebitEauBSA", ...
"PressionPalierSAG", "PuissanceSAG"];
replace_map = containers.Map( names_to_replace, replacements );
%%
var_names = names_to_replace( randi([1,4],1,8) ); % test data
new_names = arrayfun( @(key) replace_map(key), var_names, "uni", false );
reshape( new_names, [],1 )
outputs
ans =
8×1 cell array
{'PuissanceSAG' }
{'DebitEauBSA' }
{'PressionPalierSAG'}
{'TonnageBSA' }
{'PuissanceSAG' }
{'DebitEauBSA' }
{'PressionPalierSAG'}
{'PressionPalierSAG'}
>>
Surprise, I expected a string array as output. containers.Map (R2018b) doesn't seem to fully support strings.
  1 件のコメント
Bill Tubbs
Bill Tubbs 2021 年 2 月 1 日
Thanks, but the original source of the names is a cell array (from table.Properties.VariableNames) so I think cellfun is the best option as per my comment on the other answer.

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

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by