Function for Script. I need to write a Function that selects the positive and negative numbers from a matrix. How to write this?

I need to write a Function that selects the positive and negative numbers from a matrix. How to write this?

 採用された回答

dpb
dpb 2015 年 1 月 21 日
function [p,n]=splitsigns(x)
% return positive/negative values from array x in vectors p/n, respectively
p=x(x>0);
n=x(x<0);
This one excludes 0; pick where you want those if do...

7 件のコメント

ricsf
ricsf 2015 年 1 月 21 日
Thank you!!!
ricsf
ricsf 2015 年 1 月 21 日
But, if I have a matrix with positive numbers and have to change it to negative and vice-versa?
Simple enough but need a better definition of what you need/want...
x=-x; % switch all signs
x=abs(x); % all negative are now positive
Many other choices as well, depending...
ricsf
ricsf 2015 年 1 月 21 日
I'm new in Matlab... I'm doing exercices...
Thanks!
ricsf
ricsf 2015 年 1 月 21 日
編集済み: dpb 2015 年 1 月 21 日
And if i switch the input and output values, like this:
function (x)=splitsigns(p,n)
x=p(p>=0)
x=n(x<0)
Then the second assignment overwrites the first and the result of the second yields an empty set, irregardless since you guaranteed no negatives are in x with the first.
Might as well as written
function (x)=splitsigns(p,n)
x=[];
which, overall, is pretty useless... :)
ricsf
ricsf 2015 年 1 月 22 日
Ok! So, like you have writen in the first one, just to have no doubts in this.
I've the declaration of the function, with the: Output Arg (n,p) and the Input Arg (x)
And the Variables of the funtion are: p=x(x>0); n=x(x<0);
Am I thinking correctly?
dpb
dpb 2015 年 1 月 22 日
Read the help files on functions, but in general yes. Other than I'd say that p=x(x>0); and n=x(x<0); are expressions, not variables. There are no strictly local variables in those functions, only the input/output arguments (which are, of course variables just not local).

サインインしてコメントする。

その他の回答 (1 件)

a = 0.5 - rand(3,3);
%Positive numbers
a(a>=0)
% negative numbers
a(a>0)

1 件のコメント

ricsf
ricsf 2015 年 1 月 21 日
Thank You!
But, if I have a matrix with positive numbers and have to change it to negative and vice-versa?

サインインしてコメントする。

カテゴリ

質問済み:

2015 年 1 月 21 日

コメント済み:

dpb
2015 年 1 月 22 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by