code vectorization: assign numbers or datetime/durations to cell arrays, without any loop
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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'}
Akzeptierte Antwort
Voss
am 20 Okt. 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Dates and Time finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!