Keep getting invalid expression errors - matlab

I have this code, which is taken as an example from learning material.
function sum_out = sum_of_squares(2)
sum_out = 0;
for i = 1:n;
sum_out + i*i;
end
end
However I cannot run it because I get this error message:
>> sum_of_squares
Error: File: sum_of_squares.m Line: 2 Column: 35
Invalid expression. Check for missing multiplication operator, missing or
unbalanced delimiters, or other syntax error. To construct matrices, use
brackets instead of parentheses.
Where is the problem?

The expression between parentheses in the function definition line should be the name of the parameter to the function, not a value. I think you mean:
function sum_out = sum_of_squares(n)
sum_out = 0;
for i = 1:n;
sum_out + i*i;
end
end
Then, when you execute sum_of_squares(2), inside the function the variable n will have the value 2.
More about defining functions in the doc.

After the answer above i corrected it as such
n=2
function sum_out = sum_of_squares(n)
sum_out = 0;
for i = 1:n;
sum_out + i*i;
end
end

Related

How can I declare 2-dimentional array as parameter in function In MATLAB?

I have a function that gets a matrix and do some operations on it.
but I do not know how to declare function's parameter .
this is my function Code:
function D=Shirinkage(a)
D(1,:)=a(1,:);%this is X1
for i=2:4
D(i,4)=0;
for j=1:3
D(i,j)=1/2*(a(1,j)+a(i,j));
D(i,4)=D(i,j)^2 + D(i,4); %object function
end
end
end
I tried a(4,4) instead of a (parameter of the function),but the error does not appear.
Error:
??? Input argument "a" is undefined.
Error in ==> Shirinkage at 3
D(1,:)=a(1,:);%this is X1
also I want to declare D correctly.
appreciating any help.
Edited:
i call my function from a script file , in this way:
I have a 2-dimention array(matrix) its size is : 4*4 and its name is A.
i want my function gets this matrix and do the operation on it and the result can be saved again in it.
A=Shirinkage(A)
e.x. A has this values:
A=[1,2,3,4;2,3,4,5;5,6,7,8;1,2,3,4]
The function you created is working fine. The only recommendation I have to pre-allocate the size of D as it varies in each iteration in your current code.
function D = Shirinkage(a)
D = zeros(size(a));
D(1,:) = a(1,:); %this is X1
for i = 2:4
D(i,4) = 0;
for j = 1:3
D(i,j) = 0.5*(a(1,j) + a(i,j));
D(i,4) = D(i,4) + D(i,j)^2; %object function
end
end
end
The function was called from command window by using the same matrix you have used and it gave the following output.
The error you have posted says that the function hasn't received the argument a. If your script and the function are in the same MATLAB path, this should work perfectly.

Check Position with for loop, not enough input arguments - Matlab

I made a simple function that loops between the rows and columns of an array using for loops. The loop is part of a function named checktakentest (Since I'm testing this method atm). I keep getting the error that there aren't enough input arguments.
function [spotTaken] = checktakentest(tttArray)
for h = 1:3
if tttArray(h,j) == 1
%Is spot is taken, break loop
spotTaken = 1; break;
else
spotTaken = 0;
end
for j=1:3
if tttArray(h,j) == 1
spotTaken = 1; break;
else
spotTaken = 0;
end
end
end
I tried also defining h and j previously as follows
h = [1,2,3];
j = [1,2,3];
Note that tttArray is a global variable defined in another function and its array values change in that function. A spot taken is 1, empty is 0. What arguments should I pass to the function and how do I know which ones to pass since this has been a recurring problem for me? A simple explanation would be appreciated. Note that I call the function via
checktakentest(tttArray)
Just remove the first if clause - at that point you don't have j initialized to a value, so you can't use it, yet:
function [spotTaken] = checktakentest(tttArray)
for h = 1:3
for j=1:3
if tttArray(h,j) == 1
spotTaken = 1; break;
else
spotTaken = 0;
end
end
end
If you call your function like this: checktakentest(tttArray) with tttArray beeing a mxn-matrix with m>2 and n>2 you should not get an error.
If you call it like this: checktakentest you will get the error you described (not enough input arguments).

Using a variable in the 'to' of the 'for' loop in Matlab

The general syntax for a for loop in Matlab is :
for j = 1 to 5
%body
end
I want to have a variable whose value is calculated at run time depending on the user input to be used for controlling the number of times the for loop is to be run.
So I want to have:
m = input('Some Message');
n = ....% Some Calculations using user input 'm'
for j = 1 to n
%body
end
I tried this, but am getting an error -
Undefined function 'to' for input arguments of type 'char'.
Matlab is considering the variable n as a character instead of a variable.
P.S: I am new to Matlab, I searched a lot online, but couldn't get a solution for this. Please help.
The error message seems quite readable. This it not valid Matlab syntax. You would write a for loop of n repititons like this
m = input('Some Message: ');
if strcmp(m, 'foo')
n = 7;
else
n = 5;
end
for j = 1:n
fprintf('%d\n', j);
end
Actually, have you tried this syntax:
for j=1:n
%body
end
I don't see the word "to" in the docs. So the for loop syntax you have above would not be valid Matlab syntax. The other thing to consider is that n is being interpreted as a character and not a number.

First input must be function handle error using arrayfun()

I'm trying to use arrayfun() to map a function over a cell array. The following is happening:
>> arrayfun(solveFunc, equArray)
Error using arrayfun
First input must be a function handle.
Error in solve>genGuess (line 33)
funcVals = abs(arrayfun(inFunc, xValues));
Error in solve (line 8)
x = genGuess(inFunc, varargin{1}, varargin{2});
Error in makeSolveFunc>#(func)solve(func,start,stop) (line 3)
sFunc = #(func) solve(func, start, stop);
But, the first input IS a function handle. Also... if I manually apply the function to each element of the provided cell array, everything works fine:
>> solveFunc(equArray{1})
ans =
4.7335
>> solveFunc(equArray{2})
ans =
4.7356
Does anyone know why this would be happening? I assumed that if I could manually apply the function to each element of my array, and the return type of the function was consistent and one of the allowed types (you can't for example have arrayfun return an array of function handles... I already tried doing that), it should work. Perhaps that is not the only requirement.
Here is some code that generates this error:
solve.m
function solution = solve(inFunc, start, stop)
%SOLVE solve an equation using Newton's Method
x = genGuess(inFunc, start, stop);
for i = 1:100
m = getSlope(inFunc, x);
x = (m*x - inFunc(x))/m;
end
solution = x;
end
function slope = getSlope(inFunc, x)
%SLOPE calculate the slope at a given point
inc = 1e-5;
if x ~= 0
inc = inc * x;
end
slope = (inFunc(x + inc) - inFunc(x - inc))/(2*inc);
end
function guess = genGuess(inFunc, start, stop)
%GENGUESS get an initial guess to the solution
xValues = linspace(start, stop, 101);
funcVals = abs(arrayfun(inFunc, xValues));
[~, minIndex] = min(funcVals);
guess = xValues(minIndex);
end
charEqu.m
function equ = charEqu(a)
%CHAREQU create a KP model characteristic equation with provided p
equ = #(x) x + a;
end
makeSolveFunc.m
function sFunc = makeSolveFunc(start, stop)
%MAKESOLVEFUNC return a function that solves an equation
sFunc = #(func) solve(func, start, stop);
end
test.m
pArray = 1:5;
equArray = cell(1,arrayLen);
for i = 1:5
equArray{i} = charEqu(pArray(i));
end
solveFunc = makeSolveFunc(1.1*pi, 2*pi);
alphaAArray = arrayfun(solveFunc, equArray);
I have narrowed down the error to something in genGuess(). For some reason, in the line funcVals = abs(arrayfun(inFunc, xValues)); the variable inFunc is a 1x1 cell array containing a function handle. I have no idea why that would be the case. I traced this back to the anonymous function call #(func) solve(func, start, stop); in the makeSolveFunc() function. There it is still a 1x1 cell array containing a function handle. I'm not really sure where that cell array is coming from as that function is getting called from arrayfun().
Background information on what I'm trying to do in case someone wants to suggest a better way:
I'm trying to solve equations using Newton's method. I have written a function that can solve an equation given an initial guess range. This function is the solve() function you can see in the first error message. It takes a function, and the guess range and returns a function that I'm calling solveFunc(). solveFunc() takes a function and solves it using the initial guess range previously provided.
Maybe I'm just too used to functional programming and should just use a loop.
If the arguments passed to the function handle are contents of elements of a cell array, you need to use cellfun instead of arrayfun:
cellfun(solveFunc, equArray)
This is equivalent to
for i=1:length(equArray)
out(i) = solveFunc(equArray{i});
end
since solveFunc is already a function handle.
Check where the error comes from. This line causes the error:
funcVals = abs(arrayfun(inFunc, xValues));
The first input argument is a 1x1 cell containing one function handle. This is caused because equArray is a cell, thus use cellfun as Jonas already mentioned:
pArray = 1:5;
equArray = cell(1,arrayLen);
for i = 1:5
equArray{i} = charEqu(pArray(i));
end
solveFunc = makeSolveFunc(1.1*pi, 2*pi);
alphaAArray = cellfun(solveFunc, equArray);

Matlab function return value

I have one program that has function and the problem, return value, it has too many output.
Like exempley: y = text the answer comes up
Error in text (line 2)
if nargin == 0
Output argument "array" (and maybe others) not assigned during call to "
C:\Users\name\Documents\MATLAB\text.m>text".
The program text.m reads a txt file that contains a couple of names and numbers like
exemple:
John doughlas 15986
Filip duch 357852
and so on. The program convert them to 15986 Doughlas John and so on.
function array = text(~)
if nargin == 0
dirr = '.';
end
answer = dir(dirr);
k=1;
while k <= length(answer)
if answer(k).isdir
answer(k)=[];
else
filename{k}=answer(k).name;
k=k+1;
end
end
chose=menu( 'choose file',filename);
namn = char(filename(chose));
fid = fopen(namn, 'r');
R = textscan(fid,'%s %s %s');
x=-1;
k=0;
while x <= 24
x = k + 1;
All = [R{3}{x},' ',R{1}{x},' ',R{2}{x}];
disp(All)
k = k + 1;
end
fclose(fid);
Is there anyway to fix the problem without starting over from scratch?
Grateful for all the answers!
You specify the function output argument in the definition, but you don't assign anything to it in the function body.
For example, in
function y = student(j)
your output is y. So you have to assign something to y.
Read more about functions in MATLAB.
Here is a working example.
The first part is to create a function called 'functionA' in a filename 'functionA.m'. Then put the following code inside:
function result = functionA(N,alpha)
result = 5;
return
end
The second part is to create another Matlab file(i.e. upto you to name it) or you can use the Matlab command window even. Then run the following code:
getresult = functionA(100,10);
getresult
After running you get the following answer:
ans =
5