Is it possible to add an element to a "sub array"?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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?
0 commentaires
Réponse acceptée
Kunal Kandhari
le 19 Jan 2023
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 commentaires
Jan
le 19 Jan 2023
Modifié(e) : Jan
le 19 Jan 2023
@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].
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrices and Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!