write a program that creates two vectors from x—one (call it P) that contains the positive elements of x, and a second (call it N) that contains negative. I cant create the arrays
1 view (last 30 days)
Show older comments
clear all
clc
for x=[-3.5 -5 6.2 11 0 8.1 -9 0 3 -1 3 2.5]
if x>0
P=x
elseif x<0
N=x
end
end
3 Comments
Stephen23
on 9 Sep 2017
Edited: Stephen23
on 9 Sep 2017
@Muhammad Waseem: okay, then read about for and if and indexing in the MATLAB documentation: these are covered in the Introductory Tutorials which I gave you a link to. Did you do them yet?
Try the examples. Practice. Don't give up just because the first thing you thought of does not work.
The more you read the documentation the more you will learn and the easier it will be to find information in future.
Answers (2)
Image Analyst
on 9 Sep 2017
Edited: Image Analyst
on 9 Sep 2017
Hint: use the sign() function and you can do it without logical operations or logical indexing.
0 Comments
OCDER
on 9 Sep 2017
Edited: OCDER
on 9 Sep 2017
Then try growing P and N per iteration (don't use in real codes - it's slow due to matrix creation and copying). Currently, P and N are being replaced by a single scalar value since there's no change in matrix index.
Also, if there is no positive or negative value in x, you'll never create variable P or N - this causes issues when a function needs to return P and N that were never created.
Lastly, avoid using x as the loop counter directly - this makes it hard for the function accept any x and will lead to headaches in the future.
Here's something to get you started, and use the tutorial Stephen sent you to figure out how to manipulate matrices P and N.
function [P, N] = fun(x)
P = [];
N = [];
for j = 1:length(x)
%grow P if x(j) > 0
%grow N if x(j) < 0
end
When done, try comparing the speed of this method versus using logical indices (way faster).
Good luck!
6 Comments
See Also
Categories
Find more on Matrix Indexing 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!