In Matlab, I'm trying to preallocate a global array of structures. 1. Prepending the keyword global gets an error. 2. I'm getting an error trying to preallocate the object
Eg - Subscripted assignment dimension mismatch.
Error in IronCondor (line 41) OptionsChain(MaxOptions+1) = s; % make sure compatibility
MaxOptions = 3000;
OptionsChain = struct('symbol', {}, 'expiration', {}, 'strike_price', {}, 'bid', {}, 'ask', {}, 'last', {}, 'volume', {}, 'last_time', {});
if ~isempty(OptionsChain) && isstruct(OptionsChain)
OptionsChain(MaxOptions+1) = s; % make sure compatibility
end
Do this instead:
MaxOptions = 3000;
OptionsChain = struct('symbol', {}, 'expiration', {}, 'strike_price', {}, 'bid', {}, 'ask', {}, 'last', {}, 'volume', {}, 'last_time', {});
OptionsChain = repmat(OptionsChain, MaxOptions, 1);
Your code doesn't work because OptionsChain
is originally a structure of size 1. Doing OptionsChain(MaxOptions + 1)
means that you are trying to put a structure at location 3001, where that's out of bounds.
Therefore, you can do what I did above by using repmat
to duplicate OptionsChain
3000 times so that you get 3000 elements of that structure, or in a less elegant way, you can do it in a for
loop:
OptionsChain = struct('symbol', {}, 'expiration', {}, 'strike_price', {}, 'bid', {}, 'ask', {}, 'last', {}, 'volume', {}, 'last_time', {});
s = OptionsChain;
for idx = 1 : MaxOptions-1
OptionsChain(end+1) = s;
end
The end+1
allows you to tack on something at the end of the array, and we only need to do it for MaxOptions-1
times, as we already have one instance of it created.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.