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

5 visualizzazioni (ultimi 30 giorni)
Vincent il 19 Gen 2023
Commentato: Vincent il 19 Gen 2023
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 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Kunal Kandhari il 19 Gen 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]];
##### 3 CommentiMostra 1 commento meno recenteNascondi 1 commento meno recente
Jan il 19 Gen 2023
Modificato: Jan il 19 Gen 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].
Vincent il 19 Gen 2023
That works! Thank you Jan

Accedi per commentare.

### Categorie

Scopri di più su Resizing and Reshaping Matrices in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by