如何使用电池阵列在Matlab? [英] How to use cell arrays in Matlab?

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

问题描述

我是一个初学者在使用Matlab和跨电池阵列来了,但我不知道如何使用索引它。

我已经创建了5行3 COLS通过执行以下操作的单元阵列:

  A =细胞(5,3);

现在是有可能按行首先要经过单元阵列,然后山坳怎么样一个嵌套的回路正常的阵列?

 对于i = 1:5
        对于j = 1:3
           A {I,J} = {随机} //随机数/串等
        结束
    结束


解决方案

通过电池阵列有索引的方法有两种,即括号的(即(...))和括号的(即 {...} )。

让我们创建一个单元阵列用于例子:

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

使用paranthesis索引返回单元阵列的一部分的 AS单元阵列的。例如:

  A(:,3)

返回一个2×1单元阵列

  ANS =    '一个'
    [9]

使用索引括号返回细胞的内容的,例如:

  A {1,3}

返回单个字符

  ANS =一个

您可以用括号来返回一个单细胞很好,但的它仍然是一个单元格的。您还可以使用大括号返回多个细胞,但这些回报逗号分隔的名单,这是更先进一点。

当分配给一个小区,非常类似的概念适用。如果您使用括号分配,那么你必须分配的细胞的适当大小的矩阵:

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

如果您使用括号分配一个值,那么你必须把它放在一个池(即 A(1)= 2 会给你一个错误,所以你必须做 A(1)= {2} )。因此,最好使用大括号的,那么你直接影响到单元格的内容。因此,它是正确的去

  A {1} = 2

这是等同于 A(1)= {2} 。请注意,{1} = {2},这是你所做的事,不会给一个错误,但有什么做的是你的巢细胞内的单元格这是不可能的,你是什么了。

最后,如果你里面有你的细胞之一的矩阵,MATLAB允许你直接索引到像这样的矩阵:

  A {2,2}(1)ANS =     3

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

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

A = cell(5,3);

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};

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

A(:,3)

returns a 2-by-1 cell array

ans =

    'a'
    [9]

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

A{1,3}

returns a single character

ans =

a

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.

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}

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

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.

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天全站免登陆