I have 100 2D matrix .. After each matrix, I calculate the sum of elements inside it .. I want to see only the matrices with summation result under certain value (such as: 23). How can I do this?

조회 수: 3 (최근 30일)
I have 100 2D matrix .. After each matrix, I calculate the sum of elements inside it .. I want to see only the matrices with summation result under certain value (such as: 23). How can I do this?
  댓글 수: 3
Stephen23
Stephen23 2017년 5월 10일
@Mahmoud Ahmed: storing them as separate variables is not a good way to write code. It will make your code slow, buggy, complicated, and hard to debug:
The best solution is to store your data in one 3D array. Then your task is trivially easy using indexing.

댓글을 달려면 로그인하십시오.

답변 (3개)

Star Strider
Star Strider 2017년 5월 10일
편집: Star Strider 2017년 5월 10일
I have no idea how your matrices are stored or organised.
One approach:
M3 = randi(3, 5, 5, 10); % Create Data
N = size(M3,3);
for k1 = 1:N
MN = M3(:,:,k1); % Define Matrix For This Loop Iteration
Msum = sum(MN(:)); % Matrix Sum
Mtx(k1) = k1 * (Msum < 23); % Save Index If ‘Msum < 23’, Else 0
end

James Tursa
James Tursa 2017년 5월 10일
편집: James Tursa 2017년 5월 10일
E.g., if they were stored in a 3D array:
>> m = randi(10,3,3,5) % some random data
m(:,:,1) =
5 8 7
5 8 7
7 3 2
m(:,:,2) =
2 4 8
5 6 3
10 3 6
m(:,:,3) =
7 6 3
9 2 9
10 2 3
m(:,:,4) =
9 4 7
3 2 5
10 3 4
m(:,:,5) =
9 10 8
6 3 4
6 8 6
>> x = sum(reshape(m,[],size(m,3)))<50 % logical indexes where 2D sum is < 50
x =
0 1 0 1 0
>> s = m(:,:,x) % the 2D subsets that have the desired sum
s(:,:,1) =
2 4 8
5 6 3
10 3 6
s(:,:,2) =
9 4 7
3 2 5
10 3 4

Stephen23
Stephen23 2017년 5월 10일
편집: Stephen23 2017년 5월 10일
Well, this is trivial if you store your data correctly in one array:
>> A = randi(8,2,2,100); % one hundred 2x2 matrices
>> idx = sum(sum(A,1),2)>23;
>> A(:,:,idx)
ans(:,:,1) =
7 2
8 8
ans(:,:,2) =
8 2
8 8
ans(:,:,3) =
4 7
8 8
ans(:,:,4) =
8 7
3 7
ans(:,:,5) =
8 4
8 4
ans(:,:,6) =
5 7
5 7
ans(:,:,7) =
3 8
8 5
ans(:,:,8) =
1 8
8 7
ans(:,:,9) =
4 6
7 8
ans(:,:,10) =
8 5
5 7
ans(:,:,11) =
8 7
6 4
ans(:,:,12) =
7 6
8 3

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by