try ,catch, and continue commands in for loop, and storing for loop data in a matrix

조회 수: 52 (최근 30일)
Yeeun Son
Yeeun Son 2020년 10월 27일
편집: Jon 2020년 10월 27일
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.
  1. 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?
  2. 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!

답변 (1개)

Jon
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

카테고리

Help CenterFile Exchange에서 MATLAB Mobile Fundamentals에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by