Avoid a "loop for" to add multiple "datetime" elements to a cell array
조회 수: 1 (최근 30일)
이전 댓글 표시
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
dpb
2022년 10월 26일
편집: dpb
2022년 10월 26일
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.
답변 (1개)
Benjamin Thompson
2022년 10월 24일
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]}
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!