iterate over a vector in a for loop
658 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I am trying to loop through a matrix - my model has no problem looping through the bandwidths "bw" but i get an error when looping through the priors, because prior has vectors of values
the input of prior works in the format when not using a for loop...
prior = [0.427,0.226,0.347];
but i want the model to run through 3 different types of prior probabilities, as below
the error i get is: Error using classreg.learning.classif.FullClassificationModel.processPrior (line 264)
Prior probabilities must be a vector of length 3.
when i print prior i get
priors =
0.3300 0.3300 0.3300
0.4270 0.2260 0.3470
0.2000 0.2000 0.6000
bandwidths = [0.2, 0.5, 1];
priors = [0.33 0.33 0.33; 0.427 0.226 0.347; 0.2 0.2 0.6];
global mymatrix
for f=1:length(bandwidths);
for l=1:length(priors);
bw= bandwidths(f);
p = priors(l)
Mdl = fitcnb(x_train_crossval,y_labels_train_crossval,'ClassNames', class_names,'PredictorNames',predictor_names,'Prior',p,'Width',bw);
0 Commenti
Risposte (2)
Jan
il 21 Nov 2018
Avoid length, but use size with a specified dimension.
for f = 1:size(bandwidths, 2)
for l = 1:size(priors, 1)
bw = bandwidths(f);
p = priors(l, :);
priors(l) is a scalar, but the error message explains, that a [1 x 3] vector is required.
0 Commenti
Umar
il 30 Giu 2024
Hi Catherine,
To resolve the error and correctly loop through different sets of prior probabilities, you need to adjust how the priors variable is accessed within the loop. Instead of iterating over rows of the priors matrix, you should extract a single row vector for each iteration.
Here is the corrected code snippet:
global mymatrix
for f = 1:length(bandwidths) for l = 1:size(priors, 1) % Iterate over rows of priors bw = bandwidths(f); p = priors(l, :); % Extract a single row of priors Mdl = fitcnb(x_train_crossval, y_labels_train_crossval, 'ClassNames', class_names, 'PredictorNames', predictor_names, 'Prior', p, 'Width', bw); end end
By using p = priors(l, :), you can access each row of the priors matrix as a single row vector, satisfying the requirements of the fitcnb function.
Hope this will help resolve your issue.
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!