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 views (last 30 days)
Show older comments
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 Comments
Stephen23
on 10 May 2017
@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.
Answers (3)
Star Strider
on 10 May 2017
Edited: Star Strider
on 10 May 2017
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
0 Comments
James Tursa
on 10 May 2017
Edited: James Tursa
on 10 May 2017
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
0 Comments
Stephen23
on 10 May 2017
Edited: Stephen23
on 10 May 2017
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
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!