How do I make a loop write to an asymetric pre-allocated array?
Mostra commenti meno recenti
Hello,
I have the following situation. I have a function that can be expressed as y = f(x)*exp(g(x)*t). I would like to plot this function in surface form for ,say, x= .001:.001:1 and t = 0:.01:5. So far my script works when it looks like this:
x = 1:10;%Excitation energies
M=zeros(10,10);%Pre-allocate 10 by 10 array
for i= x%Repeat for vaues of N
t = 1:10;%Time M(i,:)= (3 * i ^ 2 + 2 * i + 3) * exp(-.02 * t);%decay function
end
surface(N,t,M)
shading flat
but I would like for it to run on with the .001:.001:1 and 0:.01:5. The problem I am having is that if I change the pre-allocation array to accommodate the 1000 values of x and 500 values of t the scrip no longer works and I receive the following error message:
Subscripted assignment dimension mismatch.
I get this message regardless of which pre-allocation dimension I change to 1000 or 500. If you can help me out here I'd appreciate it. If possible, can I get an explanation of where I am going wrong?
Risposta accettata
Più risposte (3)
dpb
il 9 Ago 2013
x=[1:10]; %Excitation energies
M=zeros(length(x)); %Preallocate array
for i=x
t = 1:10
M(i,:)= (3*i^2 + 2*i + 3)*exp(-0.02*t);
end
Indeed, you allocated a square array for the results so if you change one or the other lengths you'll have a mismatch. Using the inner array in conjunction w/ a loop on a single value on the outer is also kinda klunky; this is perfect location for meshgrid and writing your function to be evaluated w/ vector inputs. The "dot" operators are needed there. It's also handy to make a function handle for the function...
% make a function handle -- NB the .*
>> f=@(x,t) ([(3*x.^2 + 2*x + 3).*exp(-0.02*t)]')
f =
@(x,t)([(3*x.^2+2*x+3).*exp(-0.02*t)]')
>> % set up data ranges
>> x=[1:10]; t=[1:10];
>> [X,Y]=meshgrid(x,t);
>> z=f(X,Y);
>> all(all(z==M)) % had done your loop solution earlier...
ans = % confirms got same answer
1
>> x=[0.001:0.001:1]; t=[0:0.01:5]; % your other ranges...
>> [X,Y]=meshgrid(x,t);
>> z=f(X,Y);
>> surface(t,x,z)
NB: last reordering -- to keep orientation or your loop solution also note the ' transpose on the function result. If don't care about that, then can return to natural order.
Chris
il 12 Ago 2013
0 voti
1 Commento
dpb
il 12 Ago 2013
Again, PLEASE use the comment section for comments/questions/etc., and reserve the ANSWER section for actual answers to the question posed.
It would be a_good_thing (tm) to move these two answers to comments and then I'll followup and delete the complaints to clean up.
If going to the trouble of using the forum might at least try to make it useful as possible by not cluttering up.
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!