Comparing elements in a vector
Show older comments
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 Comments
Steven Lord
on 10 Nov 2020
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
on 10 Nov 2020
Edited: James Tursa
on 10 Nov 2020
David Hill
on 10 Nov 2020
Look at this:
x=[2 3 4];
a=sqrt(x);
logical(nnz(a==floor(a)));
Joel Bovin
on 10 Nov 2020
Edited: James Tursa
on 10 Nov 2020
James Tursa
on 10 Nov 2020
Edited: James Tursa
on 10 Nov 2020
@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
on 10 Nov 2020
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
on 10 Nov 2020
Misread that one. How about:
logical(nnz(ismember(x,x.^2)));
David Goodmanson
on 11 Nov 2020
Edited: David Goodmanson
on 11 Nov 2020
any(x' == x.^2, 'all')
uses more memory than most techniques but still for a vector of length 1000 it's just 8 MBytes
Accepted Answer
More Answers (0)
Categories
Find more on Exponents and Logarithms 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!