Clear Filters
Clear Filters

How to reshape data in 4-D array correctly?

3 views (last 30 days)
Erfan Lessan
Erfan Lessan on 27 Nov 2023
Edited: Stephen23 on 27 Nov 2023
For debugging purposes, I've loaded the following table data into my MATLAB script, I want to arrange my table data into a 4-d array. x, y, z, w are my independent variables, and v is my dependent variable.
I want to be able to access the data in v through my 4d array in the following fashion: v_reshaped(1,1,1,1) = 1, v_reshaped(1,1,1,2) = 2, v_reshaped(1,1,2,1) = 3
However, with the script I've written, the data appears as follows: v_reshaped(1,1,1,1) = 1, v_reshaped(1,1,1,2) = 9, v_reshaped(1,1,2,1) = 5
I've put my MATLAB script here for reference, can you show me how I can get the reshaped data in the order I want?
Below is an image of my table:
I've written the following MATLAB script:
% Clear everything
clear all; close all;
% Read table from MATLAB
btable = readtable('binary_lut_test.xlsx');
x.val = btable.x; y.val = btable.y;
z.val = btable.z; w.val = btable.w;
v.val = btable.v;
% Unique values from table
x.uni = unique(x.val); y.uni = unique(y.val);
z.uni = unique(z.val); w.uni = unique(w.val);
v.uni = unique(v.val);
% Create and n-dimensional grid
[X, Y, Z, W] = ndgrid(x.uni, y.uni, z.uni, w.uni)
% Compute expected number of elements
expectedNumel = numel(x.uni) * numel(y.uni) ...
* numel(z.uni) * numel(w.uni); % Evaluates
% to 16
% Reshape data
V.a = reshape(v.val, [numel(x.uni), numel(y.uni),...
numel(z.uni), numel(w.uni)]);

Answers (1)

Stephen23
Stephen23 on 27 Nov 2023
Edited: Stephen23 on 27 Nov 2023
You can use PERMUTE like this:
v = 1:16;
z = permute(reshape(v,[2,2,2,2]),[4,3,2,1]);
z(1,1,1,1)
ans = 1
z(1,1,1,2)
ans = 2
z(1,1,2,1)
ans = 3

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!