How to make it a one line code?
Mostrar comentarios más antiguos
matrix= [1 0 -1 0.001 4; 5.9 -1 3.15 1 1.11 ] ;
cell_conv = (num2cell(matrix));
find_one = abs( matrix ) == 1 ;
cell_conv(find_one)={'hey'}
2 comentarios
KSSV
el 6 de Dic. de 2017
You can striagh away use:
cell_conv(abs( matrix ) == 1)={'hey'}
oshawcole
el 6 de Dic. de 2017
Editada: Walter Roberson
el 15 de Oct. de 2023
Respuesta aceptada
Más respuestas (1)
Jos (10584)
el 6 de Dic. de 2017
Here is another but shorter two-liner using a functional programming approach for anonymous function:
matrix= [1 0 -1 0.001 4; 5.9 -1 3.15 1 1.11 ]
iif = @(varargin) varargin{2 * find([varargin{1:2:end}], 1, 'first')}() ;
% functional programming of a "if ... elseif ... else" construction
out = arrayfun(@(X) iif(isequal(abs(X),1), @() 'hey', true, @() X), matrix, 'un', 0)
3 comentarios
Walter Roberson
el 6 de Dic. de 2017
Editada: Walter Roberson
el 15 de Oct. de 2023
I think that may be the first usable iif that I have seen in MATLAB. (I remember someone posting one a few years ago but I had my doubts about whether it would work.)
Jos (10584)
el 7 de Dic. de 2017
Credits should go to Loren Shure
Walter Roberson
el 8 de Dic. de 2017
Ah, I remember now why I had forgotten Loren's solution: it was because I cannot think of any way of tricking MATLAB to return something for commands that return no output. For example if one of the branches was
@(x) set(handles.push7, 'Value', x)
and the other branch was
@(x) fprintf('hey')
then the fprintf() officially returns the number of bytes emitted so it can be used in arrayfun, but the set() has no output and cannot be used, not even when 'uniform', 0 is used.
I suppose I could write a real function
function yelm = empty(function_handle);
function_handle();
yelm = [];
end
and then code with
@(x) empty( @() set(handles.push7, 'Value', x) )
But I dislike having to write true functions to implement functional programming.
I know in HG2 that I could write
handles.push7.Value = x
and that returns handles.push7, but assignment in functional programming is ugly in MATLAB... though you can get this particular one to work:
newval = arrayfun(@(x) subsasgn(handles.push7, struct('type','.','subs','Value'), x),randi(7,1,5))
The output variable is mandatory in this situation.
Categorías
Más información sobre Data Type Identification en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!