How to cleanup/fix my mapping of cell-array MATLAB code so I do not hit a recursive limit?
3 views (last 30 days)
Show older comments
I have to solve a problem where I have to take a vector for ex [1 2 3] and map it using a table such that 1 = [1 1], 2 = [4 6 8], 3 = [6 9 12 15] (a shorter example of actual problem) So my function ideally would be convert([1 2 3]) = [1 1 4 6 8 6 9 12 15]
My thinking process is that I have to make the vector a cell array first so that I can replace the values to others that different dimensions, and then convert cell array back to vector/matrix. This is what I have so far
y = num2cell(x);
for n = 1:length(x)
if y{n} == 0
y{n} = [0 2];
elseif y{n} == 1
y{n}= [1 1];
elseif y{n} == 2
y{n} = [4 6 8];
elseif y{n} == 3
y{n} = [6 9 12 15];
elseif y{n} < 0
y{n} = 1 - convert(-(x+1));
end
output = cell2mat(y);
end
end
Everything works fine if my input has the positive values of 0, 1 , 2, or 3 in the initial vector. However, I need to have this condition where if the vector has a negative entry (x), the negative entry gets entered such that y{n} = 1 - convert(-(x+1)) However, when I do this, I get an error of hitting recursive limit. Is there a way to fix my code such that it will work with negative values and not produce an error? Also, is there a way to do it without using a for or while loop? Thanks
PS: Maybe to clarify, I'll give an example of input vector with a negative entry of -1 convert([1 2 3 -1]) = [1 1 4 6 8 6 9 12 15 1 -1]
Basically because the -1 entry will be computed in the formula 1 - convert(-(-1+1)), which then becomes 1 - convert(0) which becomes 1- [0 2], finally to [1 -1]
Answers (2)
Andrei Bobrov
on 12 Mar 2013
x = [1 2 3 -1];
d0 = 0:3;
d = {[0 2] , [1 1] , 4:2:8, 6:3:15};
tp = x < 0;
x(tp) = -(x(tp)+1);
out = cell(size(x));
[a,ii] = ismember(x,d0);
out = d(ii(a));
out(tp) = cellfun(@(x)1-x,out(tp),'un',0);
out = [out{:}];
0 Comments
Jan
on 12 Mar 2013
Edited: Jan
on 12 Mar 2013
You do not want:
y{n} = 1 - convert(-(x+1))
but
y{n} = 1 - convert(-(y{n}+1))
Calling the function with the complete input x must cause an infinite recursion, when x contains positive elements also.
3 Comments
Jonathan Sullivan
on 12 Mar 2013
The more correct way to check if something is a row vector is as follows:
sz = size(x); % Get the size of the array
sz(2) = []; % Remove the second dimension
isRow = all(sz == 1); % Check that all other dimensions have length == 1
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!