MATLAB: How would you write a function that operates on both character and numerical arrays

character arraysfunction

function [Appended] = reverseAppend(vectorVal)
B = [];
for i = 1:length(vectorVal)
B(i) = vectorVal(i);
B(i+length(vectorVal)) = vectorVal(length(vectorVal)-i+1);
end
Appended = B;
end
so far i can write it to individually work for a numerical array (let B = [ ]) and for a character array (let B = [' ']) however I am unsure how write so it can work for either a character or numerical array. any help would be much appriciated

Best Answer

  • The simple answer to your question is do NOT define B before the loop, i.e.:
    function B = reverseAppend(vectorVal)
    % NO B!
    for k = 1:length(vectorVal)
    B(k) = ...
    end
    end
    and then MATLAB will implictly create B with the appropriate class on the first iteration. Tested:
    >> reverseAppend('ABC')
    ans =
    ABCCBA
    >> reverseAppend(1:3)
    ans =
    1 2 3 3 2 1
    But your code is very inefficient, because you are expanding B on each iteration:
    Simpler and much more effiicient would be to make more effective use of indexing:
    >> revAp = @(v)[v,v(end:-1:1)];
    >> revAp('ABC')
    ans =
    ABCCBA
    >> revAp(1:3)
    ans =
    1 2 3 3 2 1