Shaibal Ahmed
Shaibal Ahmed

Reputation: 189

Change variable value inside loop in MATLAB

How can I change the value of 'StartRow' and 'EndRow' inside the loop?

for k = 1:11
filename = 'file.txt';   
...

startRow = 1422; %1564, 1706, 1848, 1990, 2132, 2274, 2416, 2558, 2700, 2842 
endRow = 1562; %1704, 1846, 1988, 2130, 2272, 2414, 2556, 2698, 2840, 2982
... 

f=figure;
plot(...);

saveas(f,sprintf('fig%d.png',k));

end

Upvotes: 0

Views: 194

Answers (3)

Sairus
Sairus

Reputation: 394

starts = [1422, 1564, 1706, 1848, 1990, 2132, 2274, 2416, 2558, 2700, 2842];
ends = [1562, 1704, 1846, 1988, 2130, 2272, 2414, 2556, 2698, 2840, 2982];

for k = 1:11
    ...
    startRow = starts(k);
    endRow = ends(k);
    ...
end

Upvotes: 1

Siva Srinivas Kolukula
Siva Srinivas Kolukula

Reputation: 1241

Keep startRow and endRow outside the loop and call them inside the loop using loop index.

startRow = [1422 1564, 1706, 1848, 1990, 2132, 2274, 2416, 2558, 2700, 2842] ;
endRow = [1562 1704, 1846, 1988, 2130, 2272, 2414, 2556, 2698, 2840, 2982];
n = length(startRow) ;
for k = 1:n
    filename = 'file.txt';
    thestart = startRow(k) ;
    theend = endRow(k) ;
    ...

...

f=figure;
plot(...);

saveas(f,sprintf('fig%d.png',k));
end

Upvotes: 1

Amritbir Singh Gill
Amritbir Singh Gill

Reputation: 386

You can store all values of startRow and endRow in a list right before the for loop and then iterate through the list to change the value of these variables inside the loop.

startRowList = [1422, 1564, 1706, 1848, 1990, 2132, 2274, 2416, 2558, 2700, 2842];
endRowList = [1562, 1704, 1846, 1988, 2130, 2272, 2414, 2556, 2698, 2840, 2982];

for k = 1:11
    filename = 'file.txt';   
    ...

    startRow = startRowList(k);
    endRow = endRowList(k);
    ... 

    f=figure;
    plot(...);

    saveas(f,sprintf('fig%d.png',k));
end

Upvotes: 1

Related Questions