How to match matrix elements for a condition?
조회 수: 6 (최근 30일)
이전 댓글 표시
I am working on App Designer. I have a matrix and want to match the elements 3 by 3 with a condition. The condition is that addition of 3 elements must be near at a value.
I already can match them by making the addition from minimum to maximum, but it does not seem to be optimal. So, I want them to be around a value.
댓글 수: 2
Dyuman Joshi
2024년 4월 22일
Use tolerance to compare -
in = [3 3.3 3.6 3.9];
check = 3.5;
tol = 0.3;
out = abs(in-check)<tol
채택된 답변
Torsten
2024년 4월 23일
편집: Torsten
2024년 4월 23일
If A becomes larger, this brute-force way of solving will become intractable.
A = [15 25 36 17 48 59 31 64 18 21 97 84 31 64 15];
target = 100;
C = nchoosek(1:numel(A),3);
P = arrayfun(@(i)sum(A(C(i,1:3))),1:size(C,1));
[~,I] = sort(abs(P-target));
sums = arrayfun(@(i)sum(A(C(I(i),:))),1:numel(I));
sums = sums(sums==sums(1));
n = numel(sums);
result = unique(sort(A(C(I(1:n),:)),2),'rows')
추가 답변 (1개)
Hassaan
2024년 4월 22일
Assuming a 1-dimensional array. Will check for sums of three consecutive elements that are close to a given value (target_sum) within a tolerance (tol).
% Example matrix (1D array)
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
% Target sum to match
target_sum = 15;
% Tolerance for matching sum
tol = 0.5;
% Length of the array
n = length(A);
% Pre-allocate the logical output array for matched cases
matches = false(1, n-2); % (n-2) because the last two elements can't start a triplet
% Iterate over the array to find matching triplets
for i = 1:n-2
% Calculate the sum of the current and next two elements
current_sum = sum(A(i:i+2));
% Check if the current sum is within the tolerance of the target sum
if abs(current_sum - target_sum) <= tol
matches(i) = true;
end
end
% Print matched triplets and their indices
matched_indices = find(matches);
for idx = matched_indices
fprintf('Match found at indices [%d, %d, %d]: [%d, %d, %d]\n', idx, idx+1, idx+2, A(idx), A(idx+1), A(idx+2));
end
-----------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Professional Interests
- Technical Services and Consulting
- Embedded Systems | Firmware Developement | Simulations
- Electrical and Electronics Engineering
Feel free to contact me.
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!