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
0 个评论
采纳的回答
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!