changing input variable loop
11 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2019-4-10
编辑:Stephen23
2019-4-10
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 ?
回答(1 个)
Guillaume
2019-4-10
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!