Matlab中构建含优化变量的求和系列函数及优化求解问题求助
Hey there, let's tackle this optimization problem step by step. From what you've described, you're working on a classification-focused optimization task with two 1×64 row vectors, and hitting snags adapting your objective function for MATLAB's Optimization Toolbox. Let's break this down into actionable fixes and best practices:
MATLAB's optimization functions (like fminunc or fmincon) require all decision variables to be packed into a single column vector—they can't handle two separate row vectors directly. Here's how to bundle and unbundle your vectors:
- Combine
R₁andR₂into a 128×1 column vector for input to the optimizer - Inside your objective function, reshape the vector back into the two 1×64 row vectors you need
Let's assume your goal is minimizing the sum of squared distances between each data point and its corresponding class vector (adjust this to match your actual objective if it's different):
function [f, grad] = classification_objective(vars, data, class1_idx, class2_idx) % Unpack the combined variable vector R1 = reshape(vars(1:64), 1, 64); R2 = reshape(vars(65:128), 1, 64); % Extract class-specific data class1_data = data(class1_idx, :); class2_data = data(class2_idx, :); % Calculate your objective function (replace with your actual formula) f = sum(sum((class1_data - R1).^2)) + sum(sum((class2_data - R2).^2)); % Optional: Provide analytical gradient for faster, more stable optimization grad_R1 = -2 * sum(class1_data - R1, 1); grad_R2 = -2 * sum(class2_data - R2, 1); grad = [grad_R1(:); grad_R2(:)]; end
Use a logical initial guess (like the mean of each class) to speed up convergence, then call the optimizer:
% Load your 1125×64 dataset (replace with your actual data loading code) data = load('your_dataset.mat'); data = data.your_data_matrix; % Define class indices class1_idx = 1:554; class2_idx = 555:1125; % Initialize variables with class means (smart starting point) init_R1 = mean(data(class1_idx, :), 1); init_R2 = mean(data(class2_idx, :), 1); init_vars = [init_R1(:); init_R2(:)]; % Configure optimizer options options = optimoptions('fminunc', ... 'Display', 'iter', ... 'Algorithm', 'quasi-newton', ... 'SpecifyObjectiveGradient', true); % Enable if you provided the gradient % Run optimization [optimal_vars, final_fval] = fminunc(@(vars) classification_objective(vars, data, class1_idx, class2_idx), init_vars, options); % Unpack the optimal vectors optimal_R1 = reshape(optimal_vars(1:64), 1, 64); optimal_R2 = reshape(optimal_vars(65:128), 1, 64);
- "Objective function won't fit the required form": This almost always means you're not bundling variables correctly, or your function returns a matrix/vector instead of a scalar. Double-check that your objective function outputs a single numerical value.
- Dimension mismatch errors: Verify that when you reshape
varsback intoR1/R2, their dimensions match your data rows (1×64). MATLAB's broadcasting works for row-vector subtraction, but older versions may need explicit replication. - Slow convergence or unstable results: Providing an analytical gradient (as in the template above) will fix this far better than relying on numerical gradients. If your objective is non-quadratic, this is critical.
If your target function uses non-squared distances (e.g., cosine similarity, Mahalanobis distance) or includes regularization terms, just modify the f calculation in the objective function. The key rules stay the same:
- Output a single scalar value
- Keep variables bundled into one column vector for the optimizer
- Provide an analytical gradient if possible
内容的提问来源于stack exchange,提问作者Sukrit

