Effacer les filtres
Effacer les filtres

code vectorization: assign numbers or datetime/durations to cell arrays, without any loop

1 vue (au cours des 30 derniers jours)
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}
a = 3×3 cell array
{[ 1]} {0×0 double} {0×0 double} {[ 1]} {0×0 double} {0×0 double} {0×0 double} {0×0 double} {0×0 double}
Case 2 : the result is not correct
a = cell(3,3);
index = [1 1
2 1
3 3];
a(index(:,1),index(:,2)) = {1}
a = 3×3 cell array
{[1]} {0×0 double} {[1]} {[1]} {0×0 double} {[1]} {[1]} {0×0 double} {[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}
a = 3×3 cell array
{3×1 datetime} {0×0 double} {3×1 datetime} {3×1 datetime} {0×0 double} {3×1 datetime} {3×1 datetime} {0×0 double} {3×1 datetime}
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'}

Réponse acceptée

Voss
Voss le 20 Oct 2022
Use sub2ind.
Case 1:
a = cell(3,3);
index = [1 1
2 1];
idx = sub2ind(size(a),index(:,1),index(:,2));
a(idx) = {1}
a = 3×3 cell array
{[ 1]} {0×0 double} {0×0 double} {[ 1]} {0×0 double} {0×0 double} {0×0 double} {0×0 double} {0×0 double}
Case 2:
a = cell(3,3);
index = [1 1
2 1
3 3];
idx = sub2ind(size(a),index(:,1),index(:,2));
a(idx) = {1}
a = 3×3 cell array
{[ 1]} {0×0 double} {0×0 double} {[ 1]} {0×0 double} {0×0 double} {0×0 double} {0×0 double} {[ 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
a = 3×3 cell array
{[20-Oct-2022 00:01:35]} {0×0 double} {0×0 double } {[20-Oct-2022 00:01:11]} {0×0 double} {0×0 double } {0×0 double } {0×0 double} {[20-Oct-2022 00:04:21]}

Plus de réponses (0)

Catégories

En savoir plus sur Dates and Time 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!

Translated by