如何在Matlab中创建和访问与给定变量列表相对应的结构? [英] How to create and access structure which structure corresponds to given variable list in matlab?

查看:119
本文介绍了如何在Matlab中创建和访问与给定变量列表相对应的结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个结构来存储数据库中的数据.

I would like to create a structure to store the data from the database.

我创建了一个函数

function result = LoadDataFromDB(query, columnNames)

其中列名代表列名列表,例如{'id','year','name'...}

where column names represents the list of column names, for example {'id', 'year', 'name'...}

执行以下查询后

ps=conn.prepareStatement(sql);
rs=ps.executeQuery();

我想填充结构,但是还没有弄清楚如何动态访问结构中的字段.

I would like to fill the structure, but haven't figured out how to dynamically access the fields in the structure.

以下是应创建并填充结构的代码段:

Here is the code piece that should create and fill the structure:

varnamelist = genvarname(columnNames);

result = cell2struct(cell(size(varnamelist(:))), varnamelist(:));
while rs.next()
    count=count+1;
    for i = 1 : length(columnNames)
        fieldname = columnNames(i);
        value = char(rs.getString(i));
          %result(count).columnNames(i)=char(rs.getString(i));
          result(count).(fieldname) = value;
    end
end

主要问题是线路

result(count).(fieldname) = value;

下面要描述的一个问题是控制台输出的副本:

To describe a problem below is the copy from the console output:

K>> result(1)

ans = 

    a: []
    b: []
    c: []

K>> result(1).('a')

ans =

     []

K>> fieldname

fieldname = 

    'a'

从上面的输出中得出结论,命令result(1).(fieldname)应该访问字段'a',但是对其进行尝试,它将返回以下错误:

Concluding from the above output, the command result(1).(fieldname) should access the field 'a' but trying it out, it returns the following error:

K>> result(1).(fieldname)
??? Argument to dynamic structure reference must evaluate to a valid field name.

有人知道如何动态填充结构吗?

Does anyone know how to fill the structure dinamically?

推荐答案

是的,有动态字段引用.您可以在此处上找到更多信息例子.

Yes, there's dynamic field reference. You can find more on it here for example.

动态引用可用于分配或引用结构中的字段,如下所示:

Dynamic reference can be used to assign or reference fields in structures like so:

fieldName = 'some_field';
your_struct.(fieldName) = fieldValue

因此,在您的情况下,这意味着将内循环主体修改为

So, in your case, that would mean modifying the inner loop body to

fieldname = columnNames{i};
value = rs.getString{i};
result(count).(fieldname) = value;

这篇关于如何在Matlab中创建和访问与给定变量列表相对应的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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