1

I have this from Mathematica and I want to create it in MATLAB

pointers = 
  Table[If[experiment[[i, 1]]^2 + experiment[[i, 2]]^2 > 1, 0, 1], {i,
     1, npoints}];

The output is for example {0, 1, 1, 1, 1, 1, 0, 0, 1, 1}, for npoints = 10.

I tried this, but it's wrong! (I am learning MATLAB now, I have a little from Mathematica though)

assign=experiment(i,1)^2 +experiment(i,2)^2;
if assign>1
    assign=0;
else assign=1;
end
pointers=assign(1:npoints);

I also did this which gives output 1, but it's wrong:

for i=1:npoints
assign=length(experiment(i,1)^2 +experiment(i,2)^2);
if assign>1
    assign=0;
else assign=1;
end
end
pointers=assign

1 Answer 1

2

In your second example, you need to index pointers, i.e. write

pointers(i) = assign;

and not call 'length' in the second line.

However, a much easier solution is to write

pointers = (experiment(:,1).^2 + experiment(:,2).^2) <= 1

With this, you're creating, inside the parentheses, a new array with the result of the sum of squares. This array can then be checked for being smaller or equal 1 (i.e. if it's bigger than 1, the result is 0), returning the result of all the comparison in the array pointers.

10
  • @George: Regarding your additional question (which should really be a comment, or an edit of your original question): The logical comparison does all the checking. Comparing an array with a scalar performs the operation on each element of the array. The IF command in Mathematica (as well as Excel) allows you to specify the result for the two outcomes. A logical comparison as I do in Matlab can only return 0 or 1, but you can easily manipulate the result so that you can obtain any other value. By the way, if you find the answer useful, please consider accepting it.
    – Jonas
    Commented Jan 20, 2011 at 21:00
  • First of all,thanks for your answer. I wanted to ask , With the <=1 in the end you are doing all the check?You don't need to execute an if statement, right? In which cases we can do things like that? Thanks again
    – George
    Commented Jan 20, 2011 at 22:08
  • @George: Have a look at the following post blogs.mathworks.com/steve/2008/01/28/logical-indexing or google for MATLAB and logical indexing.
    – zellus
    Commented Jan 20, 2011 at 22:08
  • @George please use comments for this.
    – user1228
    Commented Jan 20, 2011 at 22:08
  • "....A logical comparison as I do in Matlab can only return 0 or 1, but you can easily manipulate the result so that you can obtain any other value...." How can i do this?(manipulate it?)For example ,i have "xpoints = Table[RandomReal[], {z1, 1, np1}]",how can i write it in an one line?
    – George
    Commented Jan 24, 2011 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.