フィルターのクリア

create a function to...

1 回表示 (過去 30 日間)
Mike
Mike 2013 年 11 月 1 日
回答済み: Cedric 2013 年 11 月 1 日
Create a function *.m file that accepts a 2-dimensional array as a function input and has two function outputs. This function will use a nested loop to create one column vector that contains the sum of all the positive values in each row and another column vector that contains sum of all the negative numbers of each row. These two column vectors should be returned (sent back) to the function call.
  1 件のコメント
Mike
Mike 2013 年 11 月 1 日
編集済み: Matt J 2013 年 11 月 1 日
my attempt:
function [ positive, negative ] = Untitled2( x )
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
positive=0;
negative=0;
for k=1:length(x)
for j=1:length(x)
if x(k,j)>0
positive=positive+x(k,j)
end
if x(k,j)<0
negative=negative+x(k,j)
end
end
end
positive=positive
negative-negative
end

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

採用された回答

Cedric
Cedric 2013 年 11 月 1 日
It's not bad actually. The lines
positive=positive
negative-negative
are useless, and you want to create vectors of sums, not scalars. So one mistake is that you don't index variables positive and negative with the row index. To make it more efficient, you could even prealloc these variables: change
positive=0;
negative=0;
for
positive = zeros(size(x, 1));
negative = zeros(size(x, 1));
Another mistake is that k and j should go from 1 to the number of rows and columns of x. You can obtain them using function SIZE.

その他の回答 (1 件)

Matt J
Matt J 2013 年 11 月 1 日
Make "positive" and "negative" into vectors and index them appropriately, e.g.,
positive(k)=positive(k)+x(k,j)

カテゴリ

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