MATLAB - turning on a function within a domain

AI Thread Summary
The discussion focuses on creating a function in MATLAB to define a piecewise function. The user initially encounters an error due to incorrect syntax when trying to assign values to an array. A correct approach is provided, emphasizing the use of parentheses for indexing in MATLAB. The explanation includes how to define a function, detailing the syntax and structure required, including the use of if-else statements for conditional logic. The conversation concludes with a suggestion to consult MATLAB documentation for further learning.
Larrytsai
Messages
222
Reaction score
0
Hey guys,

I am stuck trying to create a function in matlab...

x[n] = {1 0 =< n =< 4
{0 elsewhere

so far I have this...

n = [0:4];
x[n] = 1;

but I get this error:

? x[n] = 1;
|
Error: Unbalanced or unexpected parenthesis or bracket.

and I can't figure out what is wrong.

thanks for your help.
 
Physics news on Phys.org
f you are trying to set the n-th element of x to that value, use:
x(n) = 1;

MATLAB syntax for accessing an element of an array is array_name(index) with parens, not brackets.

What I would do is something like:
Code:
function [ Y ] = X(n)
    if (0 <= n) && (n <= 4)
        Y = 1;
    else
        Y = 0;
    end
end

Edit: had some posting problems...
 
Hey thanks for the quick reply.

I am trying to set a interval of n elements to = 1.

Can you please explain "function [ Y ] = X(n)". I don't quite understand. Sorry I am kind of slow at this, as this is my first time breathing with matlab.
 
Okay. In MATLAB, to define a function (this has to be in a separate file, but more on this later), you use the following syntax:
Code:
function [output variables] = function_name(arguments)
    % function code
end
Here, "function" is the key word that tells MATLAB that you are defining a function. In the brackets are the output variables, the values the function gives back after it is run. "function_name" is what you call your function; this is up to you, but the M-file for the function must be named "function_name.m".

Inside the function you put your code. In my example:
Code:
function [ Y ] = X(n)
    if (0 <= n) && (n <= 4)
        Y = 1;
    else
        Y = 0;
    end
end
There is an if block that checks to see if the value of n is between 0 and 4. If it is, based on your original post it returns the value of 1. Otherwise, it returns 0. "&&" means and. Likewise, "||" is or, and "~" is not.

The if-else block and the function block must be closed with an "end" statement.

In your main M-file, to call the function you would just enter:
Code:
% let's say that your input variable is a vector x 
% and you want to store the output to y:
y = X(x);

Does that clear things up?
 
Yeah I understand it now.
thats great thanks a lot for your help!
 
Back
Top