Multidimensional matrix to use for loop
조회 수: 16 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Stephen23
2019년 3월 21일
편집: Stephen23
2019년 3월 22일
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
Stephen23
2019년 3월 24일
편집: Stephen23
2019년 3월 24일
"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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Argument Definitions에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!