try ,catch, and continue commands in for loop, and storing for loop data in a matrix
24 ビュー (過去 30 日間)
古いコメントを表示
Hi,
I'm having some problems with using try/catch/continue commands in for loop and storing the outcomes of the for loop in a matrix.
This is the code I wrote:
V = 31:0.5:70.5
N = numel(V)
C = cell(1,N)
for k = 1:N
x= V(k)
try
%Then I write codes for fitting a mathematical model to a graph using x values of 0 to x to obtain parameters 1-5
f1= %code for fitting graph
catch
continue
%Sometimes fitting a mathematical model to 0 to certain x value doesn't work for seme reason. I used try, catch, continue commands to just exclude the x value that doesn't work and continue with the next x iteration value.
%Then I write the code for calculating parameter 6
parameter 6 = blah blah
%For My final output inside the loop, I wrote:
output = [x f1.parameter1 f1.parameter2 f1.parameter3 f1.parameter4 f1.parameter5 parameter6]
C{k} = output
end
end
M = vertcat(C{:}) % concatenate all vectors into one matrix
I have two problems.
- The script does not give the matrix. I think that x-value that didn't work is somehow messing witht the entire matrix... How can I solve this so that the M matrix would only have x-values that worked for the mathematicl model fitting?
- I also want MATLAB to inform me at the end which x values didn't work. How can I acheive this?
Many thanks in advance!
0 件のコメント
回答 (1 件)
Jon
2020 年 10 月 27 日
編集済み: Jon
2020 年 10 月 27 日
It looks like you never assign C{k} unless there is an error. Maybe you should assign C{k} after the end statement that end the try catch block.
In general I think a try catch is best for when you get unanticipated errors. If it is a condition you can test for, like a zero in a denominator, too many iterations etc it is better to just check for that condition using an if statement and handle it more precisely.
Also it looks like you don't need to use a cell array to collect your results. You could just preallocate an array
C = zeros(N,7)
before your loop and then just directly assign
C(k,:) = [x f1.parameter1 f1.parameter2 f1.parameter3 f1.parameter4 f1.parameter5 parameter6]
If you wanted to find out what rows didn't get assigned just look for rows that are all zero. You could also do this maybe even cleaner by preallocating an array of nan of not a numbers and then checking for which rows still have NaN values, for example using isnan
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!