フィルターのクリア

For Loop 'Index Exceeds Matrix Dimensions' in Function

3 ビュー (過去 30 日間)
Areeb Hussain
Areeb Hussain 2017 年 6 月 22 日
編集済み: Jan 2017 年 6 月 22 日
I have a function file that compares a user input vector (Slt_nodes2) to the iterations of a for loop of which the number is also determined by user input (Num_nodes). If the iteration 'i' matches any of the values in Slt_nodes2, then it returns a certain equation; otherwise it returns a different equation. However, when I run it, it gives me the 'index exceeds matrix dimensions' error. I thought I took care of this when I started the loop at i=3. The reason for the '+2' in the first line of the loop is to compensate for the length of the desired output vector (DeltaO2Concentrations, a system of ordinary differential equations) starting at i=3. I suspect this is involved in producing the error. I need those to equations to remain like that, so is there any way to work around that and not get an error? Thank you.
function [ DeltaO2Concentration ] = O2Solver_beta(t,O2Conc,c,O2Leak_term,Num_nodes,Slt_nodes2)
%UNTITLED Test function used to solve 'first attempt' code.
% System of ODE diffusion equations that will be solved using 'ode45'
% function. Inputs are constant composed of universal and calculated
% constants (c), time (independent variable), O2Conc (dependent variable),
% O2Leak_term which is a separate term, and Slt_nodes2 which is a user
% input vector, and Num_nodes which is a user input integer.
%VECTOR LENGTH WILL NEED TO VARY ACCORDING TO USER INPUT%
start= 0;
terminate= Num_nodes;
DeltaO2Concentration= zeros(1,terminate-start); %Initialize Vector
cnt= 1;
for i= 3:length(DeltaO2Concentration)+2
if ismember(i,Slt_nodes2)
DeltaO2Concentration(cnt) = c*t*(O2Conc(i-2)-O2Conc(i-1)+O2Conc(i)-O2Conc(i-1))+O2Leak_term;
else
DeltaO2Concentration(cnt) = c*t*(O2Conc(i-2)-O2Conc(i-1)+O2Conc(i)-O2Conc(i-1));
end
cnt= cnt+1;
end
DeltaO2Concentration= DeltaO2Concentration.';
end

回答 (1 件)

Jan
Jan 2017 年 6 月 22 日
編集済み: Jan 2017 年 6 月 22 日
Use the debugger to find the variable, which is indexed out of its range. Type this in the command window:
dbstop if error
Then run the code again. Matalb stops in the failing line. Now inspect the current values of the variables. What is the loop counter i? What is the size of O2Conc?
Using the debugger is the way to go in case of bugs. You can set some breakpoints in the code also and step through the program line by line to inspect, what happens before the error. This helps to find differences between the intention and the code and therefore reveals teh source of bugs.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by