How can I populate an array dynamically?

4 次查看(过去 30 天)
It's a little hard to describe exactly what I'm trying to do, but the code below should make it clear. Basically I'm trying to populate an array with elements from another array, with the elements specified dynamically. The closest I've been able to come is the code below. I know it's best to avoid Eval, so if someone has a better, more elegant solution I'd love to hear it. I'm very new to Matlab, so I'm probably missing something easy. Thanks, J.C.
totalValue = rand(1, 10);
startSegmentEval = [1, 2, 3, 4, 5];
endSegmentEval = [3, 4, 5, 6, 7];
A = 'sum(totalValue(';
B = ':';
C = ')';
D = int2str(startSegmentEval');
E = int2str(endSegmentEval');
F = ';';
temp = [repmat(A, numel(D), 1), D, repmat(B, numel(D), 1), E, ...
repmat(C, numel(D), 1), repmat(C, numel(D), 1)];
a(1:5) = eval(temp);

采纳的回答

Image Analyst
Image Analyst 2013-2-1
Your temp is this:
temp =
sum(totalValue(1:3))
sum(totalValue(2:4))
sum(totalValue(3:5))
sum(totalValue(4:6))
sum(totalValue(5:7))
yet totalValue is a 2D array, not a 1D array. Can you explain what you're doing? Are you using linear indexing?
Secondly, whatever you're doing, summing values like that is not a normal, or intuitive way to do it. You'd better off just using a for loop, or a vectorized function like conv(). I could suggest code to do it with conv() if it made more sense what elements you wanted to sum in the 2D array totalValue.
  9 个评论
Image Analyst
Image Analyst 2013-2-4
No. If your window size is varying all over the place, like it's different on an element by element basis according to some function that decides the window width at that location, then you're stuck doing it very manually, not with an optimized routine like conv().
J.C.
J.C. 2013-2-4
I think I actually just figured out how to solve my problem. The code below seems to do exactly what I need. Thanks again for your help. I've learned more about matlab through this process.
totalValue = rand(1, 10);
startSegmentEval = [1, 2, 3, 4, 5];
endSegmentEval = [3, 4, 5, 6, 7];
cumulativeTotalValue = cumsum(totalValue);
offsetCumulativeTotalValue = [0, cumulativeTotalValue(1:end - 1)];
temp = cumulativeTotalValue(endSegmentEval) - offsetCumulativeTotalValue(startSegmentEval);

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by