How to create array without cells

조회 수: 13 (최근 30일)
Kristoffer Lindvall
Kristoffer Lindvall 2018년 9월 8일
편집: Kristoffer Lindvall 2018년 9월 8일
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일
편집: 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