code vectorization: assign numbers or datetime/durations to cell arrays, without any loop
3 views (last 30 days)
Show older comments
Here following I am trying to assign numbers or datetime/durations to a cell array, without any loop.
In one case the result is correct (as expected), in other two cases the results are not correct.
How to fix the cases that do not give the correct result ?
Case 1 : the result is correct
a = cell(3,3);
index = [1 1
2 1];
a(index(:,1),index(:,2)) = {1}
Case 2 : the result is not correct
a = cell(3,3);
index = [1 1
2 1
3 3];
a(index(:,1),index(:,2)) = {1}
I woud have expected the following result, as the correct one:
{[ 1]} {0×0 double} {0×0 double}
{[ 1]} {0×0 double} {0×0 double}
{0×0 double} {0×0 double} {[ 1]}
Case 3 : the result is not correct
a = cell(3,3);
index = [1 1
2 1
3 3];
b = datetime({'00:01:35'
'00:01:11'
'00:04:21'});
a(index(:,1),index(:,2)) = {b}
I woud have expected the following result, as the correct one:
{'00:01:35'} {0×0 double} {0×0 double}
{'00:01:11'} {0×0 double} {0×0 double}
{0×0 double} {0×0 double} {'00:04:21'}
Accepted Answer
Voss
on 20 Oct 2022
Case 1:
a = cell(3,3);
index = [1 1
2 1];
idx = sub2ind(size(a),index(:,1),index(:,2));
a(idx) = {1}
Case 2:
a = cell(3,3);
index = [1 1
2 1
3 3];
idx = sub2ind(size(a),index(:,1),index(:,2));
a(idx) = {1}
Case 3:
a = cell(3,3);
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) % use num2cell to convert from datetime array to cell array
0 Comments
More Answers (0)
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!