How to Use for Loop Variable outside loop

46 views (last 30 days)
I have created a loop in order to run regressions on a set of covariates based on a category variable marketshare. However, when I create a matrix of covariates based on the category it says:
Undefined function or variable 'X1'.
Error in omnitest2 (line 28)
[b,dev,stats] = glmfit(X1,Y1,'binomial');
this is the code:
for i = 1:length(marketshare(:,1))
index = 1;
for j = 1:length(X(:,1))
if X(j,10) == i
X1(index,:) = X(j,:);
Y1(index,1) = data(j,133);
index = index + 1;
[b,dev,stats] = glmfit(X1,Y1,'binomial');
David Fletcher
David Fletcher on 22 Mar 2018
Maybe it should, but does it? I've only been using Matlab a few weeks so I'm not altogether familiar with its vagaries, but it's certainly true that some languages require all code paths to return a value. Irrespective, it's easy enough to test - put an else clause on the if block and set a default value for X1 - do you then get another similar error relating to Y1

Sign in to comment.

Answers (2)

AKARSH KUMAR on 24 Jun 2020
You can try defining/declaring the variable outside the loop. Then it would work I feel.

Steven Lord
Steven Lord on 24 Jun 2020
I know this is an old question, but it popped up to the top of Answers due to AKARSH KUMAR's answer.
Consider the first iteration of the outer loop over i. I assume the variable X1 does not exist yet. If none of the elements in the tenth column of X are equal to 1, the variable X1 will never be created inside the inner loop over j since the body of the if statement will never execute. Then when you try to use X1 in the glmfit call it doesn't exist and MATLAB correctly throws an error.
Defining it outside the outer loop over i could work, but you'd run the risk of extra stuff from earlier iterations not being overwritten for future iterations. If five elements of the tenth column of X are 1, X1 will have five rows. If then only three elements of the tenth column of X are 2, elements four and five of X1 will have data from the iteration where i was 1.
So you'd probably want to define it in the inner loop over j, or eliminate that inner loop entirely using vectorization.
for i = 1:length(marketshare(:,1))
whichOnes = X(:, 10) == i;
X1 = X(whichOnes, :);
Y1 = data(whichOnes, 133);
% Consider checking that X1 and Y1 are not empty before trying to use them
[b,dev,stats] = glmfit(X1,Y1,'binomial');
% Do something with b, dev, and/or stats


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

Community Treasure Hunt

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

Start Hunting!