MATLAB从结构数组映射初始化 [英] MATLAB map initialisation from a structure array

查看:285
本文介绍了MATLAB从结构数组映射初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的目标是初始化一个Map对象,键值为double,结构为$。

我有一个类似于这样的结构数组:

  s(1)= [1,2,3]; 
s(1)='str';
s(2)= [4,5,6];
s(2)='str2';
s(3)= [7,8,9];
s(3)='str3';

然后我想创建一个地图对象,如:

  awesome = container.Map(1:3,s); 

但我收到以下错误:

 使用containers.Map的错误
指定的值类型与
此容器的预期类型不匹配。

但是,如果我这样做,它是有效的:

  awesome = container.Map(1:3,{s1,s2,s3}); 

为什么会发生这种情况,如何使结构保持为值类型? p>

解决方案

假设你的结构设置代码是这样的:

  s(1).Numbers = [1,2,3]; 
s(1).String ='str';
s(2).Numbers = [4,5,6];
s(2).String ='str2';
s(3).Numbers = [7,8,9];
s(3).String ='str3';

您可以从结构数组中创建一个地图:

  theMap = containers.Map(1:3,arrayfun(@(x)({x}),s))


My aim is to initialise a Map object with a double for key and structure for value.

I have a structure array similar to this:

s(1) = [1,2,3];
s(1) = 'str';
s(2) = [4,5,6];
s(2) = 'str2';
s(3) = [7,8,9];
s(3) = 'str3';

Then I want to create a map object like:

awesome = container.Map(1:3, s);

but I'm getting the following error:

Error using containers.Map
Specified value type does not match the type expected for
this container.

But it works if I do:

awesome = container.Map(1:3, {s1, s2, s3});

Why does this happen and how can I make it work while keeping structure as the value type?

解决方案

Assuming that your structure set-up code was intended to be something like:

s(1).Numbers = [1,2,3];
s(1).String = 'str';
s(2).Numbers = [4,5,6];
s(2).String = 'str2';
s(3).Numbers = [7,8,9];
s(3).String = 'str3';

you can make a map from the structure array with:

theMap = containers.Map( 1:3, arrayfun(@(x) ({x}), s))

这篇关于MATLAB从结构数组映射初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆