Why doesn't this program work?
Afficher commentaires plus anciens
% Weird1:
% Demonstrates some bizaar behavior of MatLAB
% Apparently scalar multiplication flips a vector from row to column.
% Or it is against the rules to put a variable on both sides of the
% equal sign; for example X(i) = 2*X(i)
% John Kirk email John.Kirk@Raymondcorp.com
clear all; clc; close all;
rpm = zeros(1000,1); % Now create all the data
for ii=1:1000;
if mod(ii,2) == 0; % is it even?
rpm(ii)=ii;
else
rpm(ii)=0;
end
end %rpm should now be vector with every other element zero
%Remove zero points for ii=2:(n-1);
count(1)=1;
count(1000)=1000;
for ii=2:(1000-1);
count(ii) = count(ii)+1;
if rpm(ii)==0;% if rpm(ii) is zero then
rpm(ii)=(rpm(ii-1)+rpm(ii+1))/2 % use average of non-zero points
else
% if it is not zero then do nothing to rpm(ii)
end
% shouldn't this statement be executed for every loop?
rpm(ii)= rpm(ii)*2;% multiply every element in rpm by 2
end% of for loop
plot(count,rpm)
% END of program *******************************************
% We have several theories for why this program does not work.
% One is that referring to rpm(ii) on both sides of the '='
% sign confuses MatLAB. The other, and almost certainly true,
% idea is we do not understand how MatLAB handles vectors and
% matrix's. We imagine that we are simply multiplying a
% scalar time each element in a vector when in fact we are
% doing matrix math and flipping a row vector into a column
% vector.
1 commentaire
Jan
le 28 Sep 2012
I cannot see any bizarre behavior. X(i)=X(i)*2 does not change the shape of X.
Réponse acceptée
Plus de réponses (1)
owr
le 28 Sep 2012
The only row vector vs. column vector issues I see here (I ran the code) is between "rpm" and "count".
rpm is defined to be a column vector with this:
rpm = zeros(1000,1);
and remains a column vector throughout all your computations.
count in indirectly defined to be a row vector - indirectly because you never initialize it with anything but this:
count(1)=1;
count(1000)=1000;
When you introduce a variable like this MATLAB automatically creates it as a row vector with exactly as many elements as it needs. The first line creates a 1 x 1 row vector, the second stretches it out to a 1 x 1000 element row vector with zeros in positions 2,...,999
1 commentaire
Yet this is not a problem or a conflict in any way. In the code, count and rpm do not interact... If count were defined as
count = zeros(1000,1);
before the assigning of the values at 1 and 1000, nothing else about the code would be different whatsoever.
Catégories
En savoir plus sur Multidimensional Arrays dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!