How to create array without cells
12 views (last 30 days)
Show older comments
Kristoffer Lindvall
on 8 Sep 2018
Edited: Kristoffer Lindvall
on 8 Sep 2018
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 Comments
Accepted Answer
Stephen23
on 8 Sep 2018
Edited: Stephen23
on 8 Sep 2018
"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 Comment
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!