changing input variable loop
조회 수: 25 (최근 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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!