Help creating a simple n-back memory test

4 次查看(过去 30 天)
Hey there, I'm trying to make a simple n-back memory test function, where n equals the amount of numbers you must remember back to (e.g. if you're shown 1 2 3 4 sequentially, when you're at 4, the answer is 2). However, I am struggling to get all my code to work. I got seperate code chunks that I tested to work seperately, but when I try to combine them to make the test work, I keep running into issues and im running out of ideas. I'm also trying to figure out how to move past the first couple of numbers so that you can immideately start guessing instead of having to go through the first couple numbers from random_numgen. The code is also supposed to work with any number of n the user chooses to input, but for the sake of testing, I chose 2. At first, I was wanting the vector of numbers to guess from to be indefinate (ends when you lose enough lives) but since im struggling to do the test itself, I gave up on that.
% n = input('How many numbers back would you like to guess? ')
% commented out for testing reasons
n = 2
random_numgen = randi(99, 1, 6) % creates vector with enough variables to guess from
for ii = 1:length(random_numgen) % should count random_numgen vec and display one by one
element = random_numgen(ii);
disp(element) % this should display numbers one by one
user = input('Answer: ');
if user == element(end-n) % this is supposed to be the answer, but it doesnt work the way I want it to
disp('Good job.')
else
disp('You''re wrong.')
end
end

回答(1 个)

Vatsal
Vatsal 2024-2-22
Hi,
The 'end' keyword in MATLAB references the last element of an array or matrix. In the given code, however, element appears to be a single number sourced from the "random_numgen" array. As such, using 'element(end-n)' will result in an error because "element" is not an array from which an index can be retrieved.
Below is the corrected code that addresses this issue:
n = 2; % Number of steps back to remember
num_trials = 6; % Total number of trials
% Pre-generate a sequence of random numbers for the trials
random_numgen = randi(99, 1, num_trials)
% Loop through each trial
for ii = 1:num_trials
% Display the current number
disp(random_numgen(ii));
% Start guessing after the sequence is long enough
if ii > n
user = input('Answer: ');
correct_answer = random_numgen(ii-n); % Get the n-back number
% Check the user's answer
if user == correct_answer
disp('Good job.');
else
disp('You''re wrong.');
end
else
% Inform the user that guessing has not started yet
disp('Not enough numbers yet for guessing.');
end
end
I hope this helps!

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by