![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/975235/image.png)
finding if number(iteration) is the sum of 2 numbers inside same array - matlab
2 次查看(过去 30 天)
显示 更早的评论
hello,
im trying to write a code that will check every number inside a 1 dimention array ( loop),
and check if the number can be summed by 2 numbers inside the array.
thanks in advance.
[EDITED] ill try to clarify.
given an array = [ 20 40 50 60 80 100]
if one of the element is the sum of 2 other element, print 1/ true
if it does not, than print 0/false
in this instance it should be true for 2 occurnaces, (20+40 = 60) and (20 + 80 = 100)
thanks in advance
1 个评论
回答(3 个)
Sam Chak
2022-4-23
编辑:Sam Chak
2022-4-23
Hi @Oren Savir
This is just a very simple example. You can turn it into a loop to check each element in the array.
% The array
X = [1 1 2; 3 5 8; 13 21 34]
X = transpose(X);
% Reshape array into vector
A = reshape(X, 1, [])
% Generate fibonacci sequence
B = fibonacci(1:length(A))
% Check true/false (1 means true, 0 means false)
tf = isequal(A, B)
X =
1 1 2
3 5 8
13 21 34
A =
1 1 2 3 5 8 13 21 34
B =
1 1 2 3 5 8 13 21 34
tf =
logical
1
0 个评论
Voss
2022-4-23
编辑:Voss
2022-4-23
Here's something that may be close to what you want to do:
X = [20 40 50 60 80 100];
ismember(X,sum(X(nchoosek(1:numel(X),2)),2))
That tells you that 20, 40, and 50 cannot be made by adding two distinct elements in X, but 60, 80, and 100 can.
Breaking down that expression, step-by-step:
disp(nchoosek(1:numel(X),2)) % generate all pairs of distinct indexes into X
disp(X(nchoosek(1:numel(X),2))) % index into X using those indexes, i.e., get the elements from X
disp(sum(X(nchoosek(1:numel(X),2)),2)) % add each pair of elements
disp(ismember(X,sum(X(nchoosek(1:numel(X),2)),2))) % see which elements of X are in the summed-pairs array
Note that this method is not "the sum of two other elements"; it is "the sum of any two elements" (really, the sum of elements at any two indices). So if you had a zero in X, then every non-zero element would be counted because it is itself+0.
X = [20 40 0 60 80 100];
disp(ismember(X,sum(X(nchoosek(1:numel(X),2)),2)))
and if you had more than one 0 element, then all elements would always be counted:
X = [20 40 0 60 80 100 0];
disp(ismember(X,sum(X(nchoosek(1:numel(X),2)),2)))
(I point it out because it's not clear what your expected result would be in those cases, based on one example with no repeated elements and no zero elements.)
0 个评论
另请参阅
类别
在 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!