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

1 次查看(过去 30 天)
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

采纳的回答

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 CenterFile Exchange 中查找有关 Function Creation 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by