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

2 ビュー (過去 30 日間)
Sim
Sim 2022 年 10 月 20 日
コメント済み: Sim 2022 年 10 月 21 日
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'}

採用された回答

Voss
Voss 2022 年 10 月 20 日
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 件)

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by