Error "too many output argument" in function
古いコメントを表示
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 件)
カテゴリ
ヘルプ センター および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!