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

3 Ansichten (letzte 30 Tage)
Sim am 20 Okt. 2022
Kommentiert: Sim am 21 Okt. 2022
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'}
1 KommentarKeine anzeigenKeine ausblenden
Sim am 21 Okt. 2022
thanks a lot @Voss! :-)

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Voss am 20 Okt. 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]}
0 Kommentare-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

Kategorien

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!

Translated by