How can I solve it: Matrix dimensions must agree.

1 回表示 (過去 30 日間)
Aimee Jin
Aimee Jin 2020 年 10 月 25 日
コメント済み: Walter Roberson 2020 年 10 月 25 日
function A = matrixCSums(M)
% M is a numeric matrix and A has the same size as M.
% Each element in A is the sum of the corresponding element in M and all
% the elements above it. Example:
% M = [ 1 3; ... A = [ 1 3; ...
% 4 5; ... 5 8; ...
% -7 2] then -2 10]
% Do NOT use any built-in functions other than size
if M ==[]
A=[];
else
A(1,:)=M(1,:); %initial row of A
[nr,nc]=size(M);
for i=2:nr
A(i,:)=A(i-1,:)+M(i,:);
end
end
When I call the function:
M = [ 1 3; 4 5; -7 2];
A = matrixCSums(M)
it says:
Error using ==
Matrix dimensions must agree.
Error in matrixCSums (line 9)
if M ==[]

採用された回答

Alan Stevens
Alan Stevens 2020 年 10 月 25 日
Replace
if M ==[]
with
if isempty(M)

その他の回答 (1 件)

drummer
drummer 2020 年 10 月 25 日
if M == []
A(M == []) = [];
else
% rest of your code here.
end
Hope that helps.
Cheers
  1 件のコメント
Walter Roberson
Walter Roberson 2020 年 10 月 25 日
M == [] is going to fail unless M is empty (but will work if M is a different size of empty).

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

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by