MATLAB: Physics Question-Building Demolition

building demolitionerrorMATLABphysicsprojectile motion

Hello, I'm writing a script to simulate building demolition using basic kinematics and Newton's law F=ma (for friction). Right now it is overly simplified, with hopes to add more to it later. I started off with just one "story" of the building being launched by the explosion. After I got that working, I was hoping to add more stories to the building via user input for them to decide how many there would be. A few errors occurred when trying to switch the code over from a single block being launched to several. The first and foremost would be and if/else statement with a nested for loop within the else. I have several of these in the beginning of the code for different variables, so it is imperative I fix the error.
towh=input('How many stories would you like the building to be');
towharr=1:towh;
if towh==2
v=15;
else
v=15*ones(size(towharr));
for i=1:towh
v=v(i)+(i-1)*0.5
end
end
When I tried to manually type the code into the command window, the array is made just like I want. But when the array is taken into the for loop I get a numel error. For some reason, the array seems to be obliterated and set to just one value..15. (Also, to explain the weird towh==2, the building needs to have at least two floors because I have made the assumption that the explosion wipes out the first floor completely.)
Later on in the code I had a for loop with nested if statements after the projectile motion so it would then show the block sliding on the ground, but since there is friction it slows after a couple seconds. Once I switched over to try to do this building demolition via array math, it doesn't work anymore.
I'll attach the code for anyone interested to help me. I'd appreciate any help for these errors I'm getting, and code not working.
Thanks in advance, Tyler

Best Answer

The array v is being obliterated, on each and every iteration of your for loop you are completely reassigning a new value to the variable v. Consider the first iteration: v is predefined as a vector, you take the first element with v(1) (a scalar), do some stuff and then assign this scalar as the the variable v . So v is now a scalar.
You probably want to index into v instead:
for i=1:towh
v(i)=v(i)+(i-1)*0.5;
end
Although to be honest this would be much tidier, faster and bug-free using fully vectorized code.
Related Question