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?
7 次查看(过去 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 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!