How do I assign 3D variables when third dimension has size one?

1 回表示 (過去 30 日間)
Thomas
Thomas 2014 年 11 月 10 日
コメント済み: Thomas 2014 年 11 月 11 日
Is this a bug? If not, how am I supposed to code this so dd1 has shape [2 3 1]?
>> sd1 = reshape(1:12,[4,3,1])
sd1 =
1 5 9
2 6 10
3 7 11
4 8 12
>> sd2 = reshape(1:24,[4,3,2])
sd2(:,:,1) =
1 5 9
2 6 10
3 7 11
4 8 12
sd2(:,:,2) =
13 17 21
14 18 22
15 19 23
16 20 24
>> for k = 1:2, dd1(k,:,:) = sd1(2*k,:,:); end
>> for k = 1:2, dd2(k,:,:) = sd2(2*k,:,:); end
>> size(dd1)
ans =
2 1 3
>> size(dd2)
ans =
2 3 2
  1 件のコメント
Matt J
Matt J 2014 年 11 月 10 日
I'm assuming dd1 was not pre-allocated prior to your for-loop.

サインインしてコメントする。

採用された回答

Matt J
Matt J 2014 年 11 月 10 日
dd1=sd1(2:2:end,:,:)
  3 件のコメント
Matt J
Matt J 2014 年 11 月 11 日
編集済み: Matt J 2014 年 11 月 11 日
I doubt it's a bug. If dd1 and dd2 are not pre-defined, then note that your for-loop results are consistent with the "shiftdim rule" that I describe in your other thread.
The bottom line - it's just one more reason why its dangerous to define or modify the size/shape of an array through assignment.
Thomas
Thomas 2014 年 11 月 11 日
Yes, your answer there (I had forgotten about that) seems to fully answer both questions. Combining the two we get the interesting MATLAB koan
>> it113 = rand(1,1,3)
it113(:,:,1) =
0.9572
it113(:,:,2) =
0.4854
it113(:,:,3) =
0.8003
>> vom113(1,:,:) = it
vom113 =
0.2785 0.5469 0.9575
>> it131 = rand(1,3,1)
it131 =
0.1419 0.4218 0.9157
>> vom131(1,:,:) = it131
vom131(:,:,1) =
0.1419
vom131(:,:,2) =
0.4218
vom131(:,:,3) =
0.9157

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by