Code some excel formulas in Matlab, in a smart way

Hey
I have a quick question, I have this excel ark where there is a column that has the following code:
q1 = 1/2 * x1 * y1
q2 = 1/2 * x2 * y2 + x1 * y1
q3 = 1/2 * x3 * y3 + x2 * y2 + x1 * y1
q4 = 1/2.............
and so on and so on.
How do I program this smart? I've tried to make a for loop, but I can't figure out how the make the 1/2 only stick to the new x-y values and not the others.

 採用された回答

Steven Lord
Steven Lord 2017 年 9 月 11 日

1 投票

This sounds vaguely homework-like so I'm not going to give the answer just a hint. I assume x1, x2, etc. refer to elements of a vector x and similarly for y1, y2, etc. Let xy be x.*y. Take a look at the cumsum function applied to xy. It doesn't get you all the way to your answer, but it gets you most of the way there.

2 件のコメント

Mikkel Ibsen
Mikkel Ibsen 2017 年 9 月 11 日
I've tried to work around some loops instead, but is the cumsum more efficient code?
This is what i have:
x = ([9;8;9;10;10]);
y = ([1;1;1;1;1]);
qadd = x.*y;
for i = 1:length(x)
q(i,1) = 0.5*qadd(i)+sum(qadd(1:i-1));
end
How would that look like in a cumsom?
José-Luis
José-Luis 2017 年 9 月 11 日
編集済み: José-Luis 2017 年 9 月 11 日
dummy = x.*y; %doesn't make much sense if y is a vector of ones
result = cumsum(dummy) - dummy./2;

サインインしてコメントする。

その他の回答 (1 件)

KL
KL 2017 年 9 月 11 日

0 投票

x = 1:5;
y = 6:10;
xy = arrayfun(@(a,b) [x(1):a;y(1):b],x,y,'UniformOutput',false);
q = cellfun(@(c) sum([0.5 ones(size(c)-1)].*prod(c)),xy,'UniformOutput',false)

2 件のコメント

Mikkel Ibsen
Mikkel Ibsen 2017 年 9 月 11 日
I can see it works, but I have no idea what is going on, and at the same time the results are cells, which I don't understand to use on further coding, is there a way to make it into a double ?
Image Analyst
Image Analyst 2017 年 9 月 11 日
There is a mat2cell() function. See the FAQ http://matlab.wikia.com/wiki/FAQ#What_is_a_cell_array.3F for an explanation of cells. However I think Steven's answer/hint is the more straightforward, less cryptic approach.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2017 年 9 月 11 日

編集済み:

2017 年 9 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by