Avoid a "loop for" to add multiple "datetime" elements to a cell array
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Given the matrix "a"
% (1) create the cell array / matrix "a"
a = cell(3,3);
% (2) add the first elements to the cell array / matrix "a"
index = [1 1
2 1
3 3];
b = datetime({'00:01:35'
'00:01:11'
'00:04:21'});
idx = sub2ind(size(a),index(:,1),index(:,2));
a(idx) = num2cell(b)
I would like not to use the loop for, here below, to add multiple elements to different cells:
% (3) add two new elements:
% - one new element inside the cell [2 3]
% - one new element inside the cell [3 3]
index2 = [2 3
3 3];
new_elements = datetime({'00:01:01'
'00:01:56'});
idx2 = sub2ind(size(a),index2(:,1),index2(:,2));
for i = 1 : size(idx2,1)
a{idx2(i)} = [a{idx2(i)} new_elements(i)];
end
% Desired output, but without the loop for
a,
5 comentarios
dpb
el 26 de Oct. de 2022
Editada: dpb
el 26 de Oct. de 2022
We don't know what "the goal" is other than the ugly-looking mess, so how can we have any suggestions about achieving same?
Is it really that your starting cell array should have been
>> N=3;
>> A=num2cell(NaT(N))
A =
3×3 cell array
{[NaT]} {[NaT]} {[NaT]}
{[NaT]} {[NaT]} {[NaT]}
{[NaT]} {[NaT]} {[NaT]}
>>
???
In that case, then at least all the elements of the cell array are datetime and you won't have the issue I raised above about having to deal with the problems of having to operate on different classes by location in the array.
But, even there I don't see a syntax without some form of a loop to do the catenation of additional elements.
Respuestas (1)
Benjamin Thompson
el 24 de Oct. de 2022
If you can make is an N by 1 cell array and do the assignment using parenthesis indexing and num2cell, then convert that to the J,K array size where J*K == N, then maybe it works for you?
b = cell(9,1);
b =
9×1 cell array
{0×0 double}
{0×0 double}
{0×0 double}
{0×0 double}
{0×0 double}
{0×0 double}
{0×0 double}
{0×0 double}
{0×0 double}
>> b(idx2) = num2cell(new_elements)
b =
9×1 cell array
{0×0 double }
{0×0 double }
{0×0 double }
{0×0 double }
{0×0 double }
{0×0 double }
{0×0 double }
{[24-Oct-2022 00:01:01]}
{[24-Oct-2022 00:01:56]}
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!