Multidimensional matrix to use for loop

16 views (last 30 days)
Gko K
Gko K on 21 Mar 2019
Commented: Gko K on 25 Mar 2019
I have a multidimensional matrix which is X.
when i type X in command window the answer is below.
X(:,:,1)
10 5 2
5 3 1
X(:,:,2)
8 4 1
7 -5 -10
X(:,:,3)
18 15 7
12 11 9
ı want to write a code using for loop to calculate some values form this matrix.
i mean
for i=1:3
a(i)=X(i)
end
something like this.
I want to get matrices as
a(1)=X(:,:,1)
a(2)=X(:,:,2)
a(3)=X(:,:,3)
How can i get it?
  2 Comments
KSSV
KSSV on 21 Mar 2019
Already your matrix X is in theat format only.
a{1} = X(:,:,1) ;
Gko K
Gko K on 21 Mar 2019
Hi friend
That not worked,
Can you take a look my comment below

Sign in to comment.

Answers (1)

Stephen23
Stephen23 on 21 Mar 2019
Edited: Stephen23 on 22 Mar 2019
for k = 1:3
X(:,:,k)
end
If you want to split into a cell array:
a = cell(1,3);
for k = 1:3
a{k} = X(:,:,k)
end
Or use num2cell or mat2cell. Also read this:
  12 Comments
Stephen23
Stephen23 on 24 Mar 2019
Edited: Stephen23 on 24 Mar 2019
"Can you try your opinion on my code above."
"I want get every X(:,:,i) and find their absolute max value in column 2 with using for loop or another way."
Personally I would get rid of the loop entirely and simply use indexing and max with its optional dimension input:
>> A = randi(99,4,3,2)
A =
ans(:,:,1) =
80 61 61
35 63 16
44 9 77
40 30 56
ans(:,:,2) =
78 76 34
15 42 21
9 38 98
57 87 79
>> squeeze(max(abs(A(:,2,:)),[],1))
ans =
63
87
"I want to get X(:,:,1), X(:,:,2), X(:,:,3), X(:,:,4), X(:,:,5), X(:,:,6) as matrices a1, a2, a3, a4, a5, a6."
You might want that, but that is a really bad way to write code. Read this to know why:
If you really want to use a loop then use a cell array, exactly as I showed you in my answer.
Gko K
Gko K on 25 Mar 2019
Ok thank you,
I am not a computer engineer or software developer. So its hard for me to think and learn as a computer engineer. Sorry if i ask so many simple or complex question.
I will try to think and solve with your opinion.

Sign in to comment.

Categories

Find more on Argument Definitions in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!