How to generate and calculate with empty values of matrix-elements

20 views (last 30 days)
I want to use logical functions to perform calculations between
matrices and don't know how to generate an empty value NaN.
I use the two matrices below and if the conditions are not satisfied,
the output should be empty:
clear all;
close all;
T = zeros(size(m)); % Make another array to fill up...
for i = 1:numel(m)
if m(i)>.5 && n(i)>.5
T(i) = m(i+1)+n(i+1);
T(i) = 'NaN';
However, I obtain the following error:
??? In an assignment A(I) = B, the number of elements in B and
I must be the same.
I hope someone know the correction of this mistake
Thank you in advance
  1 Comment
Oleg Komarov
Oleg Komarov on 28 Aug 2011
Please format the code as indicated here:

Sign in to comment.

Accepted Answer

Paulo Silva
Paulo Silva on 28 Aug 2011
T(i) = 'NaN';
is wrong, your arrays have numeric values but you are trying to put one string in the array, you can't mix numeric values with strings on arrays, do this instead:
T(i) = NaN;
See this simple example:
a=[1 2;3 4];a(1)='NaN'; %error because of what I told you
a=[1 2;3 4];a(1)=NaN; %No error
  1 Comment
Emerson De Souza
Emerson De Souza on 28 Aug 2011
Thank you Paulo,
I learned it. On the other hand, I obtain the problem with the assigning to T(i) (see comments from Oleg).
I'm trying to reformulate the problem.
Thank you for your help

Sign in to comment.

More Answers (1)

Oleg Komarov
Oleg Komarov on 28 Aug 2011
You can write directly:
instead of
but my suggestion would be to preallocate NaNs directly and delete the else part:
T = NaN(size(m))
The other problem is that you are assigning to T(i) the next values in m and n, but if i = 50 then the index will exceed the matrix dimensions.
So, what do you want to accomplish here? (you can also avoid the loop)
EDIT replaced & with |:
m = rand(10,5);
n = rand(10,5);
T = [m(2:end,:) + n(2:end,:); NaN(1,size(m,2))];
T(m(1:end-1,:) <= .5 | n(1:end-1,:) <= .5) = NaN;
Oleg Komarov
Oleg Komarov on 30 Aug 2011
You have to be careful when checking m and n, if their first element are both bigger than .5 then the first element of T is the sum of the SECOND elements of m and n.
After correcting for the | I do get consistent results. Try to replace in my example:
m = rand(3);
n = rand(3);
You'll be able to visualize and compare more easily.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by