简体   繁体   中英

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

Subscripted assignment dimension mismatch.

Matlab do not really have strings, they have char arrays. As in almost any programming language Matlab cannot define a variable without knowing how much memory to allocate. The java solution would look like this:

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

Similar to the c++ solution:

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

The c solution looks different, but is generally the same solution as in 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++. So depending on operating system, each element is either 4 (32-bit) or 8 (64-bit) bytes.

However, in Matlab matrices data is stored by value. This makes it impossible to store a N char arrays in a 1xN or Nx1 matrix. Each element in the matrix is only allowed to be of the same size as a char and be of type 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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