フィルターのクリア

i need some help on matrix operations!

1 回表示 (過去 30 日間)
mary
mary 2013 年 12 月 2 日
回答済み: Image Analyst 2013 年 12 月 2 日
if i have the index matrix a
a=[0 1 0 1 1 0 1]
and matrix b contains the actual values
v=[2 3 4 2 6 1 8]
here i'm going to check if a(i)=1 then i'm going to do the following:
a(2)=1 then sum=v(4)+v(5)+v(7)
and this will be done again to each one alone..
how to do that in an optimal way?

採用された回答

sixwwwwww
sixwwwwww 2013 年 12 月 2 日
編集済み: sixwwwwww 2013 年 12 月 2 日
do you need something like this:
a=[0 1 0 1 1 0 1];
v=[2 3 4 2 6 1 8];
for i = 1:numel(a)
sum = 0;
for j = i:numel(a)
if a(j) == 1
sum = sum + v(j);
end
end
sumArray(i) = sum;
end
  3 件のコメント
sixwwwwww
sixwwwwww 2013 年 12 月 2 日
mary try this:
a = [1 0 1 1];
v = [2 3 4 5];
sumArray = zeros(1, numel(a));
for i = 1:numel(a)
if a(i) ~= 0
for j = 1:numel(a)
if a(j) == 1 && j ~= i
sumArray(i) = sumArray(i) + v(j);
end
end
end
end
mary
mary 2013 年 12 月 2 日
yea that worked thanks

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

その他の回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 12 月 2 日
a=[1 0 1 1];
v=[2 3 4 5];
idx=find(a);
n=numel(idx);
ii=cell2mat(arrayfun(@(x) circshift(idx,[0 -x]),(1:n)','un',0));
s=sum(v(ii(:,1:n-1)),2)

Image Analyst
Image Analyst 2013 年 12 月 2 日
Mary, a vectorized, more "MATLAB-ish" way of doing it is:
% Make logical matrix.
a= logical([0 1 0 1 1 0 1])
% The "v" matix.
v = [2 3 4 2 6 1 8]
%------------------------------------------------
% Initialize
partialSum = a .* (sum(v(a)) * ones(1, length(a)))
% Subtract the v value
partialSum(a) = partialSum(a)-v(a)
In the command window, you'll see:
a =
0 1 0 1 1 0 1
v =
2 3 4 2 6 1 8
partialSum =
0 19 0 19 19 0 19
partialSum =
0 16 0 17 13 0 11

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by