Specified key type does not match the type expected for this container matlab

依然范特西╮ 提交于 2020-01-04 05:34:04

问题


I have a cell_array for which 29136x1 cell value shows in the workspace pallet. I also have a map new_labels with 4x1 Map in workspace pallet. Printing new_label on prompt gives

new_labels = 

  Map with properties:

        Count: 4
      KeyType: char
    ValueType: double

Each entry in the cell_array is the key in the map, but the problem is there a type mismatch as keyType in map is char and entries of cell_array are of type cell.

Because of this I cannot access the map and hence something like the following:

arrayfun(@(x) new_labels(x), cell_array, 'un',0);

gives error Specified key type does not match the type expected for this container.

I tried converting to char type using char_cell_array = char(cell_array) but that converts the array to be of size 29136x4 which means every entry is just one char and not really a string.

Any help appreciated.


回答1:


If you want to use the iterative way, you have to use cellfun. arrayfun operates on numeric arrays. Because cell_array is a cell array, you need to use cellfun instead of arrayfun as cellfun will iterate over cell arrays instead.

However, what you're really after is specifying more than one key into the dictionary to get the associated values. Don't use arrayfun/cellfun for that. There is a dedicated MATLAB function designed to take in multiple keys. Use the values method for that which is built-in to the containers.Map interface:

out = values(new_labels, cell_array);

By just using values(new_labels), this retrieves all of the values in the dictionary. If you want to retrieve specific values based on input keys, supply a second input parameter that is a cell array which contains all of the keys you want to access in the containers.Map object. Because you already have this cell array, you simply use this as the second input into values.

Running Example

>> A = containers.Map({1,2,3,4}, {'a','b','c','d'})

A = 

  Map with properties:

        Count: 4
      KeyType: double
    ValueType: char

>> cell_array = {1,2,2,3,3,4,1,1,1,2,2};
>> out = values(A, cell_array)

out = 

    'a'    'b'    'b'    'c'    'c'    'd'    'a'    'a'    'a'    'b'    'b'


来源:https://stackoverflow.com/questions/32919933/specified-key-type-does-not-match-the-type-expected-for-this-container-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!