-1

Introduction

Suppose I want to initialize a one-dimensional, length-N array of real numbers in MATLAB, where N is large enough for this question to matter. I will later overwrite the values, so I am mainly concerned with declaration.

I could do this in two ways:

Case A

arrayA = zeros(1,N);

Case B

arrayB = zeros(N,1);

Question

What are the performance considerations for using either of the above approaches?

  • Does one approach initialize faster than the other?
  • Does one approach use less memory (even negligibly) than the other?
  • Does one approach allow faster memory read/writes?
  • Other considerations??

For the purposes of this question, we will assume that the array is "large enough to for anything that could matter to matter", and that there could be many such arrays in a given program.

jvriesem
  • 1,859
  • 3
  • 18
  • 40
  • 1
    Try it out (benchmark it) and let us know! :) – Cecilia Jul 20 '17 at 20:44
  • 2
    Theoretically there is no difference. They all access the same amount of memory, but the rows and columns are swapped. This post can serve as an inspiration: https://stackoverflow.com/questions/36062574/why-is-reshape-so-fast/36062575 – rayryeng Jul 20 '17 at 20:52

1 Answers1

2

I can't swear to it, but my understanding is that the answer to your questions is no, no, no and maybe.

My understanding is that the base object is the matrix object, which contains (among many other things) values that identify the width and height of the matrix object, and an array of the values stored in the object. Therefore, each of these values is initialized regardless of (n,1) or (1,n) and take up the same amount of values and same amount of time to allocate and access.

For "other considerations" of you take matrix M and "vectorize it" in MATLAB by M(:) then the result will be a vector of (N,1). Normally if I have a function that inputs a vector, I'll always make sure it's a vertical vector (N,1) and have confidence that if I have it interact with other vectors that it will be in that "base" format.

Daniel Peirano
  • 514
  • 5
  • 12