Search code examples
matlabcell-array

capturing data in cell arrays in matlab


I am trying to store cell array output of a function into another cell array but couldn't do it. Here is a sample code:

clear all; close all; clc;
b1=cell(1,3);
%b1=t1()
[b1{1,1},b2{1,2},b{1,3}]=t1(); %%l1

function [ op1 ] = t1(  )
op1=cell(3,1);
op1{1}=10;
op1{2}=20;
op1{3}=30;
end

Function t1 outputs a 3x1 cell array. In line l1 I am trying to capture that array into column format array (1x3), but getting error. Anyone knows way to do this?


Solution

  • You are requesting three outputs from t1 when it only returns one. You should store the output in a temporary variable prior to saving the values into three different cell arrays. To perform that assignment you can use {:} indexing to yield a comma-separated list that you can then assign to all the different cell arrays

    output = t1();
    [b1{1,1}, b2{1,2}, b{1,3}]= output{:};
    

    Your other option is to actually return three outputs from t1

    function [out1, out2, out3] = t1(  )
        out1 = 10;
        out2 = 20;
        out3 = 30;
    end
    
    [b1{1,1}, b2{1,2}, b{1,3}] = t1();