Subtracting elements in an array
显示 更早的评论
hi there,
I have an array lets say
A=[10 9 10; 1 2 3; 4 5 6]
How can create an array like this?
B=[10-1 9-2 10-3;10-1-4 9-2-5 10-3-6]
thanks in advance!
Nikolas
采纳的回答
Star Strider
2017-1-21
编辑:Star Strider
2017-1-21
If I understand correctly what you are asking, this will work:
A=[10 9 10; 1 2 3; 4 5 6]
B = cumsum(-A(2:end,:))+A(1,:)
A =
10 9 10
1 2 3
4 5 6
B =
9 7 7
5 2 1
9 个评论
Alternately
A(1,:) - cumsum(A(2:end,:))
My first mental version was indeed in terms of negating and then cumsum, but then I realized that wasn't necessary.
Yeah that's exactly what i mean thanks a lot!!
Our pleasure!
hi again, I tried it but I get an error "matrix dimensions must agree"! any ideas how to fix it? thanks
Please post your matrix and code. That error should not occur with the sort of matrix you originally posted.
>> A=[10 9 10; 1 2 3; 4 5 6] B = cumsum(-A(2:end,:))+A(1,:)
A =
10 9 10
1 2 3
4 5 6
Error using "+ " Matrix dimensions must agree.
The most recent versions of MATLAB do this minimal expansion automatically. Somewhat less recent versions require the bsxfun function to do the same operation.
This should work for you:
B = bsxfun(@minus, A(1,:), cumsum(A(2:end,:)));
(I tested it, and it gives the same result as our eariler code versions.)
ok got it, it works! thanks again mate..!!!
Our pleasure!
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Logical 的更多信息
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!选择网站
选择网站以获取翻译的可用内容,以及查看当地活动和优惠。根据您的位置,我们建议您选择:。
您也可以从以下列表中选择网站:
如何获得最佳网站性能
选择中国网站(中文或英文)以获得最佳网站性能。其他 MathWorks 国家/地区网站并未针对您所在位置的访问进行优化。
美洲
- América Latina (Español)
- Canada (English)
- United States (English)
欧洲
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
