How to create array without cells

12 次查看(过去 30 天)
Hello!
How do you create an array that does not include cells?
for example
for i=1:3
for j=1:3
for k=1:3
A(i,j,k) = i*j*k;
end
end
end
If I specify A(2,2,1) I would like to get the scalar 2*2*1=4. And if I want a vector, A(1,1,:)=[1 2 3]. Or A(2,2,:)=[4 8 12].
Hopefully I'm making sense here. Basically I want to be able to use A(1,1,:) in the same way you would use a Matrix B(1,:).
I would appreciate the help! /Kris

采纳的回答

Stephen23
Stephen23 2018-9-8
编辑:Stephen23 2018-9-8
"Basically I want to be able to use A(1,1,:) in the same way you would use a Matrix B(1,:)."
MATLAB indexing works the same for all dimensions, so what is stopping you? When I run your code I get those exact values:
>> A(2,2,1)
ans = 4
>> A(1,1,:)
ans(:,:,1) = 1
ans(:,:,2) = 2
ans(:,:,3) = 3
>> A(2,2,:)
ans(:,:,1) = 4
ans(:,:,2) = 8
ans(:,:,3) = 12
Of course the second two example subarrays have size 1x1x3, because that is exactly the subarray that you are indexing. If you want 3x1 vectors, then use squeeze:
>> squeeze(A(1,1,:))
ans =
1
2
3
>> squeeze(A(2,2,:))
ans =
4
8
12
If you want vectors with other orientations, then use permute:
>> permute(A(1,1,:),[1,3,2])
ans =
1 2 3
>> permute(A(2,2,:),[1,3,2])
ans =
4 8 12
Of course you should also preallocate the array A before those loops, or write a vectorized version, e.g.:
[X,Y,Z] = ndgrid(1:3);
A = X.*Y.*Z
  1 个评论
Kristoffer Lindvall
编辑:Kristoffer Lindvall 2018-9-8
Awesome! Then my initial thought was correct, I just implemented it wrong in a sum. I will try using the squeeze command to see if it fixes my problem. This was really helpful. I will be playing around with this for a while so I can understand what's going on. Thanks!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by