Eka
Eka

Reputation: 15000

Decimal increments in for loop matlab

How to do decimal increments in for loop with arrays. This is the code i have written.

for i=1:0.1:10,
a(i)=i
end

Advance thanks for the help

Upvotes: 0

Views: 3859

Answers (3)

P0W
P0W

Reputation: 47784

"i want to save decimal ii value in arrays eg JJ[1]=1,jj[2]=1.1,JJ[3]=1.2 ...etc"

What's wrong with this ?

JJ=1:0.1:10;

Upvotes: 2

grantnz
grantnz

Reputation: 7423

You can do this without a counter variable if you use the helper function Enumerate.

for i=Enumerate(1:0.1:10)
   a(i.Index)=i.Value;
end

function [ output ] = Enumerate( items )
   output = struct('Index',num2cell(1:length(items)),'Value',num2cell(items));
end

This is a similar question to Neat way to loop with both index and value in Matlab

Upvotes: 3

Robert Seifert
Robert Seifert

Reputation: 25232

for indexing you need to introduce another variable, like

jj = 1;
for ii=1:0.1:10
       a(jj)=ii
       jj = jj+1;
end

or

for ii=1:1:10/0.1
       a(ii)=ii*0.1;
end

also have a look at the sub2ind function if you just want to store the counter in a vector.

another alternative. I don't know what your loop is doing, but at what I'm guessing I would do it as follows:

A = 1:0.1:10;
for ii=1:1:length(A)
       do something;
end

Upvotes: 4

Related Questions