Is it possible to add an element to a "sub array"?

2 次查看(过去 30 天)
Im not sure what the proper term for this structure is in Matlab, but I have the following variable
stateMeasurements = {[] [] [] [] []};
Every array is supposed to contain basically a pair of start time and end time, so if I want to add a measurement for State 1 for example, I would like to do something like this
stateMeasurements(1).push([5, 10]);
I can first get the sub array and add the measurement to it, but then I can put it back into stateMeasurements.
m = stateMeasurements(1);
m{end+1}=[5, 10];
stateMeasurements(1) = m % This gives an error
The error I receive is "Unable to perform assignment because the left and right sides have a different number of elements."
I know how to achieve this in other programming languages but how can I do this in Matlab?

采纳的回答

Kunal Kandhari
Kunal Kandhari 2023-1-19
Hello Vincent,
For an existing cell array stateMeasurements, you can assign a new element to the end using direct indexing. For example
stateMeasurements{6}=[10,11]
or
stateMeasurements{end+1}=[20,26]
where "end" is a special keyword in MATLAB that means the last index in the array. So in your specific case of n elements, it would automatically know that "end" is your "n".
Another way to add an element to a "cell array" is by using concatenation:
stateMeasurements=[stateMeasurements,[10,22]];
For more information, see below documentations:
  3 个评论
Jan
Jan 2023-1-19
编辑:Jan 2023-1-19
@Vincent: [] is Matlab's operator for the concatenation. "[ ]" is used to display an empty array, but of course there are no brackets anywhere. |[[20,26]] is exactly the same as [20, 26].
To obatin the wanted output:
stateMeasurements = {[] [] [] [] []};
stateMeasurements{3} = [20, 26];
Note the curly braces for the cell indexing. The same result, but slightly slower in the execution:
stateMeasurements(3) = {[20, 26]};
Now the right side creates a scalar cell array and inserts in as 3rd element of stateMeasurements. It is faster to insert the contents directly as shown above.
If you want to attach further values to this vector:
stateMeasurements{3} = [stateMeasurements{3}; [1, 2]];
Now the 3rd element of the cell vector stateMeasurements contains the matrix [20, 26; 1, 2].

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by