Error in the anonymous function
3 views (last 30 days)
Show older comments
Sorry for the basic question, but a help is much appreciated.
I'have following code below and I'm trying to select randomly single value for two or more variables from a vector of 1x24. Self is the vector, here the error appears as follwing. I also find the syntax error, however, I can't see in problem from myside.
S_r = length (Self);...
↑
Error: Incorrect use of '=' operator. To assign a value to a variable, use '='. To compare values for equality, use
'=='.
P_k = @(Self, ny)(...
S_r = length (Self,);...
R_p = randperm(S_r);...
D_i = R_p(1:ny);...
C_a(D_i)...
);
In addition, I also see syntax errors e.g., invalid syntax at '='.A'(' on line 26 might be missing')' line 26 is the first line.
And on the last line it is parse error at ')': usage might invalid syntax error
I can also attached a simple example of the whole secnario below.
Define A as a 1x24 vector
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
21, 22, 23, 24];
% Define an anonymous function that returns a random subset of n values from A
sample = @(A, n) ( ... % Use @ to define an anonymous function
N = length(A); ... % Get the size of A
P = randperm(N); ... % Generate a random permutation of the indices of A
I = P(1:n); ... % Select the first n indices from the permutation
A(I) ... % Access the corresponding values of A
);
% Define the number of iterations
iterations = 24;
% Loop for each iteration
for i = 1:iterations
% Sample two values from A and assign them to B and C
[B, C] = sample(A, 2);
% Print B and C
fprintf('Iteration %d: B = %d, C = %d\n', i, B, C);
end
0 Comments
Accepted Answer
VBBV
on 26 Jan 2024
Edited: VBBV
on 26 Jan 2024
% Define A as a 1x24 vector
AA = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
21, 22, 23, 24];
n = 2; % change the value here
N = length(AA); % Get the size of A
% Define the number of iterations
iterations = 24;
% Loop for each iteration
for i = 1:iterations
P = randperm(N); ... % Generate a random permutation of the indices of A
I = P(1:n); ... % Select the first n indices from the permutation
AA(I); % Access the corresponding values of A
% Define an anonymous function that returns a random subset of n values from A
sample = @(A, n) [N P I A]; %... % Use @ to define an anonymous function
fprintf('Iteration %d: \n', i)
% Sample two values from A and assign them to B and C
sample(AA(i), n)
% Print B and C
end
3 Comments
VBBV
on 26 Jan 2024
' ( ' and ' ) ' are parenthesis used for named function definitions. However, for anonymous function definitons they may not be needed.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!