how to use ga function to calculate a matrix

조회 수: 1 (최근 30일)
yijia
yijia 2023년 11월 4일
댓글: yijia 2023년 11월 7일
I want to use ga function to calculate a matrix with 13 × 1 shape.
In the folloing code, spectra is a 413 × 13 matrix, random_matrix is a 413 × 1 matrix.
lb = zeros(13, 1); % Lower bounds for each element of the matrix
ub = ones(13, 1); % Upper bounds for each element of the matrix
fitnessFcn = @(x) mean((spectra * x - random_matrix).^2);
options = optimset('Display', 'iter');
[xOpt, fOpt] = ga(fitnessFcn, 13, [], [], [], [], lb, ub, [], options);
I wonder how to use ga function to calculate a matrix by the function which has matrix multiplying.
The bug log is the folloing, and times. function cannot solve the problem.
Can anyone give me an example about calculating a matrix by the function which has matrix multiplying.
错误使用 *
用于矩阵乘法的维度不正确。请检查并确保第一个矩阵中的列数与第二个矩阵中的行数匹配。要单独对矩阵的每个元素进行运算,请使用 TIMES (.*)执行按元素相乘。
出错 untitled>@(x)mean((spectra*x-random_matrix).^2) (104 )
fitnessFcn = @(x) mean((spectra * x - random_matrix).^2);
出错 createAnonymousFcn>@(x)fcn(x,FcnArgs{:}) (11 )
fcn_handle = @(x) fcn(x,FcnArgs{:});
出错 makeState (58 )
firstMemberScore = FitnessFcn(state.Population(initScoreProvided+1,:));
出错 galincon (24 )
state = makeState(GenomeLength,FitnessFcn,Iterate,output.problemtype,options);
出错 ga (420 )
[x,fval,exitFlag,output,population,scores] = galincon(FitnessFcn,nvars, ...
出错 untitled (110 )
[xOpt, fOpt] = ga(fitnessFcn, 13, [], [], [], [], lb, ub, [], options);
原因:
Failure in initial user-supplied fitness function evaluation. GA cannot continue.

채택된 답변

Walter Roberson
Walter Roberson 2023년 11월 4일
When you ask for 13 variables, your function will get passed a row vector 1 x 13. Your code assumes that it will receive a column vector.
The shape you give for ub and lb does not affect the shape of the vector that is passed to your function.
  댓글 수: 1
yijia
yijia 2023년 11월 7일
Thank you very much! When i change the "spectra * x" to "spectra * transpose(x)", it works.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Genetic Algorithm에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by