如何在 Matlab 中使用元胞数组? [英] How to use cell arrays in Matlab?

查看:71
本文介绍了如何在 Matlab 中使用元胞数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用 Matlab 的初学者,遇到过元胞数组,但我不确定如何为其使用索引.

I am a beginner at using Matlab and came across cell arrays but I am not sure how to use indexing for it.

我通过执行以下操作创建了一个包含 5 行和 3 列的元胞数组:

I have created a cell array of 5 rows and 3 cols by doing the following:

A = cell(5,3);

现在是否可以像普通数组的嵌套 for 循环一样,先逐行遍历元胞数组,然后再逐行遍历?

Now is it possible to go through the cell array by row first and then col like how a nested for loop for a normal array?

    for i=1:5
        for j=1:3
           A{i,j} = {"random"} //random numbers/ string etc
        end
    end

推荐答案

对于元胞数组,您有两种索引方法,即括号(即 (...))和大括号(即{...}).

With cell arrays you have two methods of indexing namely parenthesis (i.e. (...)) and braces (i.e. {...}).

让我们创建一个用于示例的元胞数组:

Lets create a cell array to use for examples:

A = {3,   9,     'a'; 
     'B', [2,4], 0};

使用括号的索引返回元胞数组的一部分AS A CELL ARRAY.例如

Indexing using paranthesis returns a portion of the cell array AS A CELL ARRAY. For example

A(:,3)

返回一个 2×1 元胞数组

returns a 2-by-1 cell array

ans =

    'a'
     0

使用大括号的索引返回该单元格的CONTENTS,例如

Indexing using braces return the CONTENTS of that cell, for example

A{1,3}

返回单个字符

ans =

a

您也可以使用括号返回单个单元格,但它仍然是一个单元格.您也可以使用大括号返回多个单元格,但这些单元格返回为 comma分隔列表,更高级一些.

You can use parenthesis to return a single cell as well but it will still be a cell. You can also use braces to return multiple cells but these return as comma separated lists, which is a bit more advanced.

分配给单元格时,应用非常相似的概念.如果您使用括号进行分配,则必须分配一个适当大小的 cell 矩阵:

When assigning to a cell, very similar concepts apply. If you're assigning using parenthesis, then you must assign a cell matrix of the appropriate size:

A(:,1) = {1,1}

如果您使用括号分配单个值,则必须将其放入单元格中(即 A(1) = 2 会给您一个错误,因此您必须执行 A(1) = {2}).所以最好使用大括号,因为那样你会直接影响单元格的内容.所以走是正确的

if you assign a single value using parenthesis, then you must put it in a cell (i.e. A(1) = 2 will give you an error, so you must do A(1) = {2}). So it's better to use braces as then you are directly affecting the contents of the cell. So it is correct to go

A{1} = 2

这相当于 A(1) = {2}.请注意,您所做的 A{1} = {2} 不会出错,但它的作用是在您的单元格中嵌套一个单元格,这不太可能是您所追求的.

this is equivalent to A(1) = {2}. Note that A{1} = {2}, which is what you've done, will not give a error but what is does is nests a cell within your cell which is unlikely what you were after.

最后,如果您的一个单元格中有一个矩阵,那么 Matlab 允许您直接索引到该矩阵中,如下所示:

Lastly, if you have an matrix inside one of your cells, then Matlab allows you to index directly into that matrix like so:

A{2,2}(1)

ans = 

     3

这篇关于如何在 Matlab 中使用元胞数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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