How to Use for Loop Variable outside loop
27 次查看(过去 30 天)
显示 更早的评论
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;
end
end
[b,dev,stats] = glmfit(X1,Y1,'binomial');
end
3 个评论
David Fletcher
2018-3-22
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
回答(2 个)
AKARSH KUMAR
2020-6-24
You can try defining/declaring the variable outside the loop. Then it would work I feel.
0 个评论
Steven Lord
2020-6-24
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
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!