简体   繁体   English

下标分配尺寸不匹配。 Matlab中的错误

[英]Subscripted assignment dimension mismatch. error in matlab

    for i=1:30
  Name(i,1)=sprintf('String_%i',i);
end

I'm just confused what is not working here, this script seems very straightforward, wnat to build a list of strings with numbering from 1 to 30. getting error 我只是感到困惑,在这里行不通,该脚本看起来非常简单,需要构建一个编号从1到30的字符串列表。

Subscripted assignment dimension mismatch. 下标分配尺寸不匹配。

Matlab do not really have strings, they have char arrays. Matlab实际上没有字符串,它们具有char数组。 As in almost any programming language Matlab cannot define a variable without knowing how much memory to allocate. 与几乎所有编程语言一样,Matlab在不知道要分配多少内存的情况下无法定义变量。 The java solution would look like this: Java解决方案如下所示:

String str[] = {"I","am","a","string"};

Similar to the c++ solution: 与c ++解决方案类似:

std::string str[] = {"I","am","another","string"};

The c solution looks different, but is generally the same solution as in c++: c解决方案看起来有所不同,但通常与c ++中的解决方案相同:

const char* str[] = {"I","am","a","c-type","string"};

However, despite the appearances these are all fundamentally the same in the sense to that they all knows how much data to allocate even though they would not be initiated. 但是,尽管有这些表象,但从根本上讲它们都是相同的,因为即使它们不会启动,它们都知道要分配多少数据。 In particular you can for example write: 特别地,您可以例如编写:

String str[3];
// Initialize element with an any length string.

The reason is that the memory stored in each element is stored by its reference in java and by a pointer in c and c++. 原因是存储在每个元素中的内存是通过java中的引用以及c和c ++中的指针存储的。 So depending on operating system, each element is either 4 (32-bit) or 8 (64-bit) bytes. 因此,取决于操作系统,每个元素都是4(32位)或8(64位)字节。

However, in Matlab matrices data is stored by value. 但是,在Matlab矩阵中,数据是按值存储的。 This makes it impossible to store a N char arrays in a 1xN or Nx1 matrix. 这使得不可能将N char数组存储在1xNNx1矩阵中。 Each element in the matrix is only allowed to be of the same size as a char and be of type char. 矩阵中的每个元素只能与char大小相同,并且类型为char。 This means that if you work with strings you need to use the data structure cell (as also suggested by Benoit_11 ) which stores a reference to any Matlab object in each element. 这意味着,如果您使用字符串,则需要使用数据结构cell (如Benoit_11所建议),该单元在每个元素中存储对任何Matlab对象的引用。

k = 1:30;
Name = cell(length(k),1);
for i=k
    Name{i,1}=sprintf('String_%i',i);
end

Hope that the explanation makes sense to you. 希望这种解释对您有意义。 I assumed that according to your attempt you have at least some programming experience from at least one other language than matlab. 我假设根据您的尝试,您至少具有至少一种不同于matlab的语言的编程经验。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM