Storing values from for loop in array and calling functions

I am writing a function to run an m file multiple times and place all outputs into a matrix named AllSimData. I have a few issues. When I run the code below as is, the output is just the pre-allocated zeros matrix. If I try to have line 10 be AllSimData(ii,:)=MakeFakeData(n); the error is "Subscripted assignment dimension mismatch." I'm not sure how to proceed, as I am new to programming.
function [AllSimData] = catSim( SimNumber,n )
%This function will run MakeFakeData(n)the number of times specified as the
%value of SimNumber. Each output of MakeFakeData is a nx5 matrix. This
%function will concatenate each nx5 matrix vertically, creating a huge nx5
%matrix to represent multiple simulations of data generation.
AllSimData=zeros(10000,5);
for ii=1:SimNumber
MakeFakeData(n); %n=number of data points/rows in each FakeData set
AllSimData(ii,:); %Run through all specified iterations of MakeFakeData and add them to array AllSimData.
end
end

 采纳的回答

If you've got SimNumber simulations and each is n by 5, then the total output needs be--
AllSimData=zeros(SimNumber*n,5);
Then subscript AllSimData(ii,:) is one row and you're trying to smush five rows into it--that's the size mismatch error. You've got to keep a counter as to where the rows are going to go that is (ii-1)*5+1 or 1,6,11,... and the range each time is 1:5,6:10,11:15, ...
So,
i1=1; i2=n; % initialize counters
for ii=1:SimNumber
AllSimData(i1:i2,:)=MakeFakeData(n);
i1=i1+n; i2=i2+n; % increment counters
end

2 个评论

Thank you for the help on the pre-allocating! I was wondering if I could do SimNumber*n, but I started with just making a larger array than I thought I'd need until my for loop was accurate.
I'm confused about the counters. I have 5 columns in the matrix, with n number of rows in all columns. Could this work?
i1=1; i2=n; % initialize counters
for ii=1:SimNumber
AllSimData(i1:i2,:)=MakeFakeData(n);
i1=i1+n; i2=i2+n; % increment counters
end
Thanks again.
My bad; yes, that's correct; add the n rows, not the column count. Made the correction...

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by