MATLAB Answers

Error "too many output argument" in function

3 views (last 30 days)
I just have try some of applied physics here and try to run the code in Matlab R2019b. after some step, about separate the code become function. it became
Error using initSpins1
Too many output arguments.
Error in Metro2 (line 9)
spin = initSpins1(numSpinsPerDim, probSpinUp);
I also write the program right below,
numSpinsPerDim = 2^3;
probSpinUp = 0.5;
numTemps = 2^9;
kTc = 2*J / log(1+sqrt(2)); % Curie temperature
kT = linspace(0, 2*kTc, numTemps);
% Preallocate to store results
Emean = zeros(size(kT));
Mmean = zeros(size(kT));
% Replace 'for' with 'parfor' to run in parallel with Parallel Computing Toolbox.
parfor tempIndex = 1:numTemps
spin = initSpins1(numSpinsPerDim,probSpinUp);
spin = Metropolisalgo1(spin, kT(tempIndex), J);
Emean(tempIndex) = energyIsingalgo1(spin, J);
Mmean(tempIndex) = magnetizationIsingalgo1(spin);
end
and each of function like,
function initSpins1(numSpinsPerDim, probSpinUp);
spin = sign(probSpinUp - rand(numSpinsPerDim, numSpinsPerDim));
end
function metropolisalgo1(spin, kT, J);% Metropolis algorithm
numIters = 2^7 * numel(spin);
for iter = 1 : numIters
% Pick a random spin
linearIndex = randi(numel(spin));
[row, col] = ind2sub(size(spin), linearIndex);
% Find its nearest neighbors
above = mod(row - 1 - 1, size(spin,1)) + 1;
below = mod(row + 1 - 1, size(spin,1)) + 1;
left = mod(col - 1 - 1, size(spin,2)) + 1;
right = mod(col + 1 - 1, size(spin,2)) + 1;
neighbors = [ spin(above,col);
spin(row,left); spin(row,right);
spin(below,col)];
% Calculate energy change if this spin is flipped
dE = 2 * J * spin(row, col) * sum(neighbors);
% Boltzmann probability of flipping
prob = exp(-dE / kT);
% Spin flip condition
if dE <= 0 || rand() <= prob
spin(row, col) = - spin(row, col);
end
end
end
function energyIsingalgo1(spin, J);
% The mean energy
sumOfNeighbors = ...
circshift(spin, [ 0 1]) ...
+ circshift(spin, [ 0 -1]) ...
+ circshift(spin, [ 1 0]) ...
+ circshift(spin, [-1 0]);
Em = - J * spin .* sumOfNeighbors;
E = 0.5 * sum(Em(:));
Emean = E / numel(spin);
end
function magnetizationIsingalgo1(spin);
Mmean = mean(spin(:));
end
How should I do to fix the error? thanks

  0 Comments

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 22 Oct 2020
Edited: Stephen Cobeldick on 22 Oct 2020
"How should I do to fix the error?"
If you want a function to return an output then the it must be defined in the function declaration, e.g.:
function spin = initSpins1(numSpinsPerDim, probSpinUp)
% ^^^^^^^ you need this!
This is explained in the function documentation (which also shows how to return multiple outputs):

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!