How to create array without cells

11 Ansichten (letzte 30 Tage)
Kristoffer Lindvall
Kristoffer Lindvall am 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

Akzeptierte Antwort

Stephen23
Stephen23 am 8 Sep. 2018
Bearbeitet: Stephen23 am 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 Kommentar
Kristoffer Lindvall
Kristoffer Lindvall am 8 Sep. 2018
Bearbeitet: Kristoffer Lindvall am 8 Sep. 2018
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!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by