Using Variable inside For loop Iteration

Hi Folks,
I am trying to use a variable inside a for loop iteration, as seen below in the code I have pasted in. I guess the variables don't quite matter too much, but I will explain a bit. Particle_rad is simply a number and obstnew is a large matrix. i is taken as the row value and ii is taken as the column value of the matrix. Essentially, I want to initialize at (i,ii) and then add the particle_rad value to i in order to place a 3 at the new location. Obviously I get an error when I try to do this, and here is the error: Subscript indices must either be real positive integers or logicals. I understand the error, but I am just wondering if there is any way around this. If anyone requires any more explanation, please let me know.
Thank you, Sean
if obstnew2(i,ii) == 3
for j = 1:particle_rad
obstnew2(i+(particle_rad),j) = 3;
obstnew2(i+(particle_rad),-j) = 3;

답변 (1개)

Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan 2017년 2월 15일

0 개 추천

You're probably getting the error because of the line obstnew2(i+(particle_rad),-j) = 3. You have "minus j" which makes the index negative.

댓글 수: 3

Sean Farrell
Sean Farrell 2017년 2월 15일
Thanks for the answer! Unfortunately though, I am getting the error for obstnew2(i+(particle_rad),j) = 3; line. This leads me to believe that I cannot add a variable to an index value. Any ideas on how I could get around this?
You can do that as long as i+(particle_rad) is a real positive integer. Are you sure the value of particle_rad is a non-negative integer?
Stephen23
Stephen23 2017년 2월 15일
편집: Stephen23 2017년 2월 15일
"I cannot add a variable to an index value"
You certainly can add variable to create an index. An index is a variable, just like any other, and can be created by adding other variables, multiplying, or any other numeric operation. Of course the variable when it is used as an index must be a integer greater then zero. A common beginner error is to supply a non-integer value.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2017년 2월 15일

편집:

2017년 2월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by