How do I prevent rewriting of data in my structure array within a for loop?

Hello,
I have a for loop running as show below. The goal is for the data to be added as a new row to the fields with every loop run. Currently, it is rewriting previous rows from the loops run as 0. How do I preserve the data collected while adding to it?
if buttoncounter<=5
for i=1:buttoncounter
r1(buttoncounter)=randi(length(gettrialone));
r2(buttoncounter)=randi(length(paytrialone));
set(messaget1g1,'String',sprintf('Collect $%d and pay a fine of $%d',...
[gettrialone(r1(buttoncounter)),paytrialone(r2(buttoncounter))]))
get(buttonA,'Enable');set(buttonA,'Enable','off');
get(buttonB,'Enable');set(buttonB,'Enable','off');
datat1g1(buttoncounter).Button_Pressed(buttoncounter,1)='B';
datat1g1(buttoncounter).Earned(buttoncounter,1)=gettrialone(r1(buttoncounter));
datat1g1(buttoncounter).Fee(buttoncounter,1)=paytrialone(r2(buttoncounter));
end
end

Answers (1)

Perhaps something like:
if buttoncounter<=5
LEN = numel(data1g1);
for i=1:buttoncounter
% ...
data1g1(buttoncounter).Button_Pressed(LEN+buttoncounter,1)='B';
% ...
end
end

5 Comments

Hi, the code is still converting the previous data to zero and just adding the new data as fresh rows.
UPDATE - fixed using persistent variables.
It is diifficult to diagnose this without your current code (all of it, if that's possible) and some data to work with. Is the code doing something when buttoncounter >5?
The code was rewriting over my data which was collected with every consecutive button push. I however, fixed it by making my data variabkle persistent - This was the data with every button click just gets added as a new row.
@Keerthana Natarajan it sounds like your code is in a callback/function. Variables created in a function are forgotten when the function completes. Persistent variables are one option to set scope; best practice is to pass the variables you want to keep into and out of the function as arguments.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 12 Nov 2022

Commented:

on 15 Nov 2022

Community Treasure Hunt

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

Start Hunting!