How to add scalar to empty matrix?

3 ビュー (過去 30 日間)
Random goose
Random goose 2018 年 12 月 9 日
編集済み: Stephen23 2018 年 12 月 10 日
Can I make an empty matrix behave as zero when adding/subtracting/ a scalar with such an empty matrix?
Suppose you have the following for loop
result = zeros(5,1);
for k=1:5
result(k) = k^2 + ones(k-1,1)*5;
end
On the very first loop I will have 1^2 + []*5, and this will return an empty vector. I can obviously change the starting point for k to 2 to avoid this issue. However the problem I have is a more complicated version, and in some cases the starting point for the loop will be random. I would like to obtain k^2+[]*5 = k^2; treat the empty matrix as a zero, but matlab will just return an empty vector. Is there any way of converting an empty matrix into zero, and keeping the matrix if its not empty?
  2 件のコメント
Stephen23
Stephen23 2018 年 12 月 10 日
編集済み: Stephen23 2018 年 12 月 10 日
You noticed the flaw in your code for k=0, but notice also that your code will not work for any k>1, because on this line:
result(k) = k^2 + ones(k-1,1)*5;
you try to allocate the RHW into one element of the LSH array result, so this will not work if the RHY is a two element vector, or a three element vector, etc., because you cannot force multiple elements of an array into one element of another array. An numeric array element contains one value, and that is all.
In fact your code will only work when k=1.
Random goose
Random goose 2018 年 12 月 10 日
Thank you for your response. I think I just used a bad example to motivate my question. I was wondering if there is a special command that would allow me to convert empty matrices to zero, so that the addition/multiplication/subtraction with a scalar will go through. I am trying to avoid "if isempty()" statements, which would be another possible solution suggested on the forum.

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

採用された回答

Stephen23
Stephen23 2018 年 12 月 10 日
編集済み: Stephen23 2018 年 12 月 10 日
Where val is possibly empty, and the ouput should be a scalar:
tmp = [val,0];
tmp(1)
If the output could be non-scalar, then if with isempty is probably the clearest solution.

その他の回答 (1 件)

KSSV
KSSV 2018 年 12 月 10 日
result = cell(5,1);
for k=1:5
k1 = ones(k-1,1)*5 ;
if isempty(k1)
result{k} = k^2 ;
else
result{k} = k^2 + k1 ;
end
end
YOu cannot put the rsult into a matrix......store them in a cell.
  1 件のコメント
Random goose
Random goose 2018 年 12 月 10 日
Thank you for your response. Using "if isempty()" is a good solution, but I wonder if this could slow down the computation. I am running this on a more complicated structure that has quite a few of conditional statements. If possible, I would like to avoid if statements. Is there any command for converting empty matrices into a zero scalar?

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

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by