MATLAB Cell Array Manipulation

Exercise 2: Cell Array Creation and Resizing

MATLAB Code

Answer: clear; % Create a 2x2 cell array ca = cell(2); % Assign values to the cell array ca{1,1} = 'a'; ca{1,2} = 11; ca{2,1} = 'b'; ca{2,2} = 22; ca % Create a new 3x2 cell array canew = cell(3,2); canew{1,1} = ca{1,1}; canew{1,2} = ca{1,2}; canew{2,1} = 'c'; canew{2,2} = 33; canew{3,1} = ca{2,1}; canew{3,2} = ca{2,2}; % Assign to old variable clear ca ca = canew; clear canew ca

Expected Output

ca = 
    'a'    [11]
    'b'    [22]

ca = 
    'a'    [11]
    'c'    [33]
    'b'    [22]

Code Explanation

This MATLAB code demonstrates how to create, manipulate, and resize cell arrays. Cell arrays are useful for storing different data types in the same array.

Step 1: Initialize a 2x2 Cell Array

The code creates a 2x2 empty cell array using the cell(2) function.

Step 2: Assign Values

Each cell is populated with either a character or a numeric value using curly brace indexing {}.

Step 3: Display the Cell Array

The current state of the cell array is displayed by calling the variable name without a semicolon.

Step 4: Create a Larger Cell Array

A new 3x2 cell array is created, and values from the original array are copied along with new values.

Step 5: Replace Original Array

The original variable ca is cleared, assigned the new array, and the temporary variable is cleared.

The final result is a 3x2 cell array containing a mix of character and numeric data, demonstrating how MATLAB cell arrays can be dynamically resized and restructured.



For more details, please contact me here.