# Incompatible indices after trying to add multiple output rand functions.

1 vue (au cours des 30 derniers jours)
Petch Anuwutthinawin le 4 Juil 2021
Réponse apportée : dpb le 4 Juil 2021
%% I wrote this code as a monte carlo simulation in order to sum the randomly generated weights of 15 boxes.
%% Each box is the sum of X and Y, made in a way where all the boxes are different (using rand commands).
%% My error is when I try to add X and Y, it says i cannot because the indices of the sides are not compatible.
%% How do I make them compatible?
N = 1000 ;
Box = zeros(N,1);
Relativefreq=zeros(N,1);
count=0 ;
for i=1:1000;
X=sum(1.2+0.18*randn(260,15));
Y=sum(1.1+(1.5-1.1)*rand(140,15));
Box(i)=(X+Y); %it says the indices the left and right of this are not comptible.
if Box(i)>=7430
count = count + 1 ;
end
Relativefreq(i) = count/i ;
end
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

dpb le 4 Juil 2021
As Image Analyst pointed out in his response earlier, FORMAT YOUR CODE PROPERLY! It is much more error-prone when things aren't indented and harder to debug. While MATLAB doesn't care, your (and our) time is valuable...
WtX=sum(1.2+0.18*randn(15*260,1)); % weight of X parts in 15 boxes
WtY=sum(1.1+(1.5-1.1)*rand(15*140,1)); % weight of Y parts in 15 boxes
WtPallet=WtX+WtY; % total pallet weight
is the code I provided; NB the difference in the argument to the random number generators.
What you've written gives
>> whos X Y
Name Size Bytes Class Attributes
X 1x15 120 double
Y 1x15 120 double
>>
which you can't put into a single variable element and is not the total weight of the pallet to which you're comparing it.
You could do it this way if you do want to keep the statistics for the individual boxes as well as the pallet, but you've still got to then compute the overall sum of the weights to get the pallet weight.
Again, it would be far easier to keep stuff straight if you would use meaningful variable names that reflect what is actually in the variable instead of being generic to a fault. I like shorter variable names, too, but one can take things too far to that extreme as well.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Optimization dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by