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 CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by