Code overwrites results in for loop. Cannot figure out how to index.

1 次查看(过去 30 天)
I've run into a problem with the following code, which is part of a for loop with index k.
if strcmp(l(1:5),'alpha') %Get row starting with alpha
l = fgetl(fid); % get next line
first_data = str2num(l);
alpha_beta = [first_data(1) first_data(3)]; % store alpha and beta
end
My issue is that the alpha_beta variable keeps overwriting with each iteration of the for loop. Ideally I'd like to save first_data(1) and first_data(3) from each iteration in alpha_beta. I tried a few things with indexing including
alpha_beta{k} = [first_data(1) first_data(3)];
but because it's a 'double' it won't allow brace indexing. I can't seem to find any alternatives, so if anyone has a suggestion it would be much appreciated.

采纳的回答

Stephen23
Stephen23 2019-11-20
Either
alpha_beta(k,1) = first_data(1);
alpha_beta(k,2) = first_data(3);
or
alpha_beta(k,1:2) = first_data([1,3]);
And remeber to preallocate alpha_beta before the loop:

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by