changing input variable loop
16 views (last 30 days)
Show older comments
Hi All,
I am very new to matlab.
I have an issue where i need to change range of an input variable on each loop. I have attached the input data above.
There are multiple ranges within this input variable that i need to calculate through the same loop.
ie
Range1 = Input variable(9203:9805)
Range2 = Input variable(93596:104564)
I have a lot of these ranges to run through.
Is there a way of running a loop function and changing the range each time, and outputting that data as A1,A2,A3 etc?
I have read elsewhere that dynamic variables and bad, and ive been trying to get round this issue, but i cant seem to work it out.
Thank you
Joe
3 Comments
Stephen23
on 10 Apr 2019
Edited: Stephen23
on 10 Apr 2019
Dynamic variable names are one way that beginners force themselves into writing slow, complex, obfuscated, buggy code that is hard to debug. Read this to know why:
Dynamic variable names are also very easy to avoid: just use simple and efficient indexing, or a table, or a structure.
How are these ranges defined / generated ?
Answers (1)
Guillaume
on 10 Apr 2019
I won't belittle the point about numbered variables. Read Stephen and Jan links. Suffice to say, if you start numbering or naming your variables in any serial manner, you need to stop and rethink.
As said, it's most likely that you don't need a loop. You certainly don't need one for something as simple as averaging even if it's averaging different ranges. But without seeing your code, we can't guess what you're doing exactly.
If your processing code is a script, then first thing you need to do is convert it into a function that accepts either a range vector (eg. the vector 9203:9805 for your first range) or the start and end of the range (eg. 9203 and 9805 for your first range. Once that is done, calling your function for each range is trivial.
ranges = [9203 9805
935596 104564
... more rows
];
result = cell(size(range, 1), 1); %assuming the function returns variable size output. If scalar then
%result = zeros(size(range, 1), 1);
for row = 1:size(ranges, 1)
result{row} = yourfunction(ranges(row, 1), ranges(row, 2)); %if taking range start and end
result{row} = yourfunction(ranges(row, 1):ranges(row, 2)); %if taking a range vector
end
The loop can also be replace by an arrayfun:
ranges = [9203 9805
935596 104564
... more rows
];
result = arrayfun(@yourfunction, ranges(:, 1), ranges(:, 2), 'UniformOutput', false);
But again, it's most likely that none of this needed and you could just use plain indexing if you're just averaging.
1 Comment
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!