I think you need to read things like the syntax of various tools, like while. You also need to learn the syntax of just how to write a function.
The goal here is to build a random walk function, that takes nsteps. (Learn to use descriptive variable names. MATLAB does not charge more for the extra chars. But your code will improve, because you can now read it better, and THAT means you can debug your code more easily and faster.) So +1 or 1, with equal probability. The walk will start at 0. And you want the function to return the end point of that random walk? Perhaps better, to see that the code is working, is if we return the entire randomwalk. But I'll follow what you did.
First, a function starts with the word FUNCTION. Look at my code for randomwalk1. I'll follow a style like you used in this first attempt. I used a for loop, as well as an if. (Why do you use a for loop here. A while loop is appropriate when you don't know how many steps the loop will run. A for loop applies when you DO know that. Here, you know the walk has nsteps steps.)
I could probably do some statistics that will tell me the distribution of the final state of such a random walk, since the final state is essentially the sum of iid binomial random variables. But those walks seem reasonable.
Can we improve on that code? Of course. Taking baby steps, consider randomwalk2. randi can generate other results than simply 0 and 1. Use that capability!
I suppose I never really needed to generate step as a separate variable.
But this begs the question of why I even need a loop!
Next, we might consider if sometimes, we really want to generate multiple parallel random walks. And that suggests randomwalk4.
function finalstate = randomwalk1(nsteps)
finalstate = finalstate - 1;
finalstate = finalstate + 1;
function finalstate = randomwalk2(nsteps)
finalstate = finalstate + step;
function finalstate = randomwalk3(nsteps)
steps = randi([-1 1],1,100);
function finalstate = randomwalk4(nsteps,nwalks)
if (nargin < 2) || isempty(nwalks)
steps = randi([-1 1],nwalks,100);
finalstate = sum(steps,2);