Comparing elements in a vector
古いコメントを表示
Hello!
I need to check if a squared element exists in the vector as another element.
for example x=[2 3 4]
so the squared value of 2 would be 4 which is in the vector and would result in a returnation of y=true.
This vector is quite small and I need a solution to work for bigger vectors but you get the idea of what I need.
I would love to find some documentation on this if you have it available, been searching for hours without finding anything that I can make work. I tried using find() among other things but couldn't make it work.
8 件のコメント
Steven Lord
2020 年 11 月 10 日
This sounds like a homework assignment. If it is, show us the code you've written to try to solve the problem and ask a specific question about where you're having difficulty and we may be able to provide some guidance.
If you aren't sure where to start because you're not familiar with how to write MATLAB code, I suggest you start with the MATLAB Onramp tutorial (https://www.mathworks.com/support/learn-with-matlab-tutorials.html) to quickly learn the essentials of MATLAB.
If you aren't sure where to start because you're not familiar with the mathematics you'll need to solve the problem, I recommend asking your professor and/or teaching assistant for help.
I will give one hint: ismember may be useful.
Joel Bovin
2020 年 11 月 10 日
編集済み: James Tursa
2020 年 11 月 10 日
David Hill
2020 年 11 月 10 日
Look at this:
x=[2 3 4];
a=sqrt(x);
logical(nnz(a==floor(a)));
Joel Bovin
2020 年 11 月 10 日
編集済み: James Tursa
2020 年 11 月 10 日
James Tursa
2020 年 11 月 10 日
編集済み: James Tursa
2020 年 11 月 10 日
@Joel: Your double for-loop solution looks good. But note that this logic can be short-circuited. As soon as you get your first y=true condition, you can return from the function.
if x(a).^2==x(i)
y=true;
return
end
James Tursa
2020 年 11 月 10 日
And yet another method to consider is to stack x and x.^2 into one variable and then see if the unique( ) function drops any elements of this variable.
David Hill
2020 年 11 月 10 日
Misread that one. How about:
logical(nnz(ismember(x,x.^2)));
David Goodmanson
2020 年 11 月 11 日
編集済み: David Goodmanson
2020 年 11 月 11 日
any(x' == x.^2, 'all')
uses more memory than most techniques but still for a vector of length 1000 it's just 8 MBytes
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Exponents and Logarithms についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!