I have a function file, I want to input an array and evaluate each cell in that array. How do I alter my function file to do this?
1 回表示 (過去 30 日間)
古いコメントを表示
function x=isoddm(a)
if isnan(a)==1
x=-1;
elseif mod(a,2)==0.5
x=-1;
elseif mod(a,2)==1.5
x=-1;
elseif mod(a,2)==0
x=0;
elseif mod(a,2)==1
x=1;
else
x=nan;
end
The purpose of this function is to see whether an array element is an integer or not and if it is, is it an even or odd number. The problem I am having is that it cannot evaluate each cell in an array individually.
採用された回答
その他の回答 (1 件)
Walter Roberson
2013 年 4 月 7 日
Use logical indexing. For example,
x = -1 * ones(size(a));
x( mod(a,b) == c ) = d;
3 件のコメント
Walter Roberson
2013 年 4 月 7 日
There is no such thing as an "if loop". There are "for loop" and "while loop" and "if statement". The body of an "if" executes either 0 times (for false) or 1 time (for true); loops are for executing the body multiple times.
In my example, b, c, and d are values you will need to determine for your purposes. For example in one case, "b" might be 2. I deliberately did not give examples of what values you would use for b, c, and d because most of your original code was wrong (and still is, in your code that you Accepted.)
You basically have 3 cases: one case is all the situations that produce -1, one case is the situations that produce 0, and one case is the situations that produce 1. Your series of "if" statements can be replaced by an initialization of x, followed by three statements of the form
x( mod(a,b) == c ) = d;
with appropriately chosen "b", "c", and "d" (e.g., in one case, d would be -1, in another it would be 0, in the third it would be 1.)
To give an example, if you were required to give -3 for numbers of the form of 7x+5, then
x( mod(a, 7) == 5 ) = -3;
参考
カテゴリ
Help Center および File Exchange で Global or Multiple Starting Point Search についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!